1.概念
根据不同的条件需要执行不同的 SQL 命令.称为动态 SQL
MyBatis 中动态 SQL 在 mapper.xml 中添加逻辑判断等.
3. If 使用
<select id="selByAccinAccout" resultType="log"> select * from log where 1=1 <!-- OGNL 表达式,直接写 key 或对象的属性.不需要添加任 何特字符号 --> <if test="accin!=null and accin!=''"> and accin=#{accin} </if> <if test="accout!=null and accout!=''"> and accout=#{accout} </if> </select>
4.1 当编写 where 标签时,如果内容中第一个是 and 去掉第一个 and
4.2 如果<where>中有内容会生成 where 关键字,如果没有内容不 生成 where 关键字
4.3 使用示例
比直接使用<if>少写 where 1=1
<select id="selByAccinAccout" resultType="log"> select * from log <where> <if test="accin!=null and accin!=''"> and accin=#{accin} </if> <if test="accout!=null and accout!=''"> and accout=#{accout} </if> </where> </select>
5. <choose><when><otherwise>
5.1 只要有一个成立,其他都不执行.
5.2 代码示例
<select id="selByAccinAccout" resultType="log"> select * from log <where> <choose> <when test="accin!=null and accin!=''"> and accin=#{accin} </when> <when test="accout!=null and accout!=''"> and accout=#{accout} </when> </choose> </where> </select>
6. <set>用在修改 SQL 中 set 从句
6.1 作用:去掉最后一个逗号
6.2 作用:如果<set>里面有内容生成 set 关键字,没有就不生成
6.3 示例
<update id="upd" parameterType="log" > update log <set> id=#{id}, <if test="accIn!=null and accIn!=''"> accin=#{accIn}, </if> <if test="accOut!=null and accOut!=''"> accout=#{accOut}, </if> </set> where id=#{id} </update>
7. Trim
7.1 prefix 在前面添加内容
7.2 prefixOverrides 去掉前面内容
7.3 suffix 在后面添加内容
7.4 suffixOverrieds 去掉后面内容
7.5 执行顺序去掉内容后添加内容
7.6 代码示例
<update id="upd" parameterType="log"> update log <trim prefix="set" suffixOverrides=","> a=a, </trim> where id=100 </update>
8.<bind>
8.1 作用:给参数重新赋值
8.2 场景:
模糊查询
8.3 示例
<select id="selByLog" parameterType="log" resultType="log"> <bind name="accin" value="'%'+accin+'%'"/> #{money} </select>
9.<foreach> 标签
9.1 循环参数内容,还具备在内容的前后添加内容,还具备添加分 隔符功能.
9.2 适用场景:in 查询中.批量新增中(mybatis 中 foreach 效率比较 低)
insert into log VALUES (default,1,2,3),(default,2,3,4),(default,3,4,5)
factory.openSession(ExecutorType.BATCH);
9.3 示例
<select id="selIn" parameterType="list" resultType="log"> select * from log where id in <foreach collection="list" item="abc" open="(" close=")" separator=","> #{abc} </foreach> </select>
10. <sql>和<include>
<sql id="mysql"> id,accin,accout,money </sql>
<select id=""> select <include refid="mysql"></include> from log </select>
文章来源: https://blog.csdn.net/mengxianglong123/article/details/90368356