原文链接:https://blog.csdn.net/qw463800202/article/details/103221651
原文链接:Mybatis常用语法汇总
1.1、在项目中涉及多个动态查询条件,一般我们是通过 where 1 = 1,这样可以处理where后面对应条件全空的情况,我们可以使用
<where>
<if test="keyword != null">
and title like concat('%',trim(#{keyword}),'%')
</if>
</where>
<where>
<if test="name != null">
or name=#{name}
</if>
<if test="keyword != null">
or title like concat('%',trim(#{keyword}),'%')
</if>
</where>
1.2、在项目中涉及多个动态update条件时,传统的项目需要我们去除最后一个条件的逗号,但是在mybatis中我们可以使用
UPDATE user
<set>
<if test ='null != name'>name = #{name},</if>
<if test ='null != email'>email = #{email},</if>
<if test ='null != headUrl'>head_url = #{headUrl},</if>
<if test ='null != linkData'>link_data = #{linkData},</if>
<if test ='null != createTime'>create_time = #{createTime},</if>
<if test ='null != updateTime'>update_time = #{updateTime}</if>
</set>
1.3、动态if else语句,在mybatis中使用choose、when、otherwise来处理,如下代码
<select id="selectInCondition" parameterType="order" resultType="order">
select * from order where amount gt;= #{admount}
<choose>
<when test="merchantId != null">
and merchant_id = #{merchantId};
</when>
<when test="area != 0">
and area = #{area};
</when>
<otherwise>
or 1 = 1;
</otherwise>
</choose>
</select>
二、mybatis大于、小于、等于
mybatis 中 SQL 写在mapper.xml文件中,而xml解析 < 、>、<=、>= 时会出错,这时应该使用转义写法,如下
< | <= | > | >= | & | ‘ | “ |
---|---|---|---|---|---|---|
< | <= | > | >= | & | ' | “ |
三、mybatis循环标签
3.1、循环查询in语句,代码如下
<select id="findBy" resultMap="BaseResultMap">
select * from user where user_id in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
3.2、批量插入使用循环,代码如下
<insert id="insertList" parameterType="java.util.List">
insert into user
( name,sex,email,remark)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.name},
#{item.sex},
#{item.email},
#{item.remark}
)
</foreach>
</insert>
四、重复的sql片段整合在一起使用include标签
定义:
<sql id="Base_Column_List" >
id, name, url, priority, logo, img
</sql>
引用:
<include refid="Base_Column_List" />
五、一对一查询、一对多查询,查看对应博文 SpringBoot整合mybatis实现一对一、一对多查询