??根据不同的条件,需要执行不同的SQL 命令.称为动态SQL。例如如下需求,我们需要根据姓名和手机号去查询person的数据,那么:
select * from personselect * from person where name = 'xxx'select * from person where phone = 'xxx'select * from person where name = 'xxx' and phone = 'xxx'??如果上面这种处理逻辑要在service或dao中进行处理时,会比较麻烦,这个时候,就可以使用上动态SQL了,利用MyBatis 中的动态SQL 在mappxml中添加逻辑判断等。
<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><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>??可以看到,实现同样的功能,使用<where>比直接使用<if>少写了where 1=1
??只要有一个
<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>??根据上面的sql,当accin 和accout 都不是null 且都不是""时,即当两个<when>都判断成立时,生成的sql 中只有where accin=?,即第一个。
??<set>用在更新(upadte)数据库的时候使用。先来直接看mapper.xml的书写:
<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>??<set>用来修改SQL 中set 从句。
<update id="upd" parameterType="log"> update log
  <trim prefix="set" suffixOverrides=",">
     a=a,
  </trim>
 where id=100
</update>??作用:给参数重新赋值
??使用场景:
????1)模糊查询
????2)在原内容前或后添加内容
??示例:
<select id="selByLog" parameterType="log" resultType="log">
  <bind name="accin" value="'%'+accin+'%'"/>
   #{money}
</select>
主要应用的其实就是in查询。
insert into log VALUES(default,1,2,3),(default,2,3,4),(default,3,4,5)2.2 openSession()必须指定
??底层是JDBC 的PreparedStatement.addBatch();
factory.openSession(ExecutorType.BATCH);<select id="selIn" parameterType="list" resultType="log">
    select * from log where id in
    <foreach collection="list" item="abc" open="(" close=")" separator=",">
        #{abc}
    </foreach>
</select><sql id="mysql">
   id,accin,accout,money
</sql><select id="">
    select <include refid="mysql"></include>
    from log
</select>原文:https://www.cnblogs.com/suhaha/p/11798299.html