动态SQL
1. if
相当与java里的if语句,只有满足条件了才会,拼接if标签内的语句,不满足就忽略if标签内的语句
-
mapper接口
public interface EmployeeMapper { List<Employee> findByXml( Employee employee); }
-
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.liyang.springredis.mapper.EmployeeMapper"> <select id="findByIdXml" resultType="cn.liyang.springredis.pojo.Employee" parameterType="cn.liyang.springredis.pojo.Employee"> select * from employee where 1=1 <if test="id != 0 "> and id = #{id} </if> <if test="word != null "> and word like concat('%',#{word},'%') </if> </select> </mapper>
2. if+where
where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
上边的语句就可以用where标签改造
select * from employee
<where>
<if test="id != 0 ">
id = #{id}
</if>
<if test="word != null ">
and word like concat('%',#{word},'%')
</if>
</where>
3. if+set
进行更新操作的时候使用if+set语句;
解决问题:如果参数是一个对象,并且seq语句是静态并且是满参,当我们只想更改对象的某一个属性时,这个属性更改了,但你还需要把其属性的值全部在赋值一份,不然为null
如果写成动态语句,可以对不更改的数据为null,因为为null的时候,动态sql不会拼接这个属性,不会对这个属性进行更新
<update id="update" parameterType="cn.liyang.springredis.pojo.Employee" >
update employee
<set>
<if test="yuangongname != null ">
yuangongname=#{yuangongname},
</if>
<if test="word != null">
word=#{word},
</if>
<if test="lineManagerId != 0">
lineManagerId=#{lineManagerId}
</if>
</set>
where id=#{id}
</update>
4. choose(when,otherwise)语句
有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句
choose <==> switch
when <==> case : 只要发现满足条件的,就执行且仅仅执行这一个条件
otherwise <==> default : 如果没有一个能满足case条件,最终会执行这个条件
<select id="query" parameterType="cn.liyang.springredis.pojo.Employee" resultType="cn.liyang.springredis.pojo.Employee">
select * from company.employee
<where>
<choose>
<when test="id != 0">
id = #{id}
</when>
<when test="word != '' and word != null">
and word = #{word}
</when>
<when test="yuangongname != '' and yuangongname != null">
and yuangongname = #{yuangongname}
</when>
<otherwise>
and bumenTableId=1
</otherwise>
</choose>
</where>
</select>
5. forEach语句
-
mapper接口
public interface EmployeeMapper { List<Employee> query (Employee employee); }
-
mapper.xml文件;
<select id="findByIds" resultType="cn.liyang.springredis.pojo.Employee" parameterType="List"> select * from company.employee where id in <foreach collection="list" index="index" item="id" open="(" separator="," close=")"> #{id} </foreach> </select>
-
[注]:
collection=“list” : 要遍历的集合名字
index=“index” : 遍历过程中的计数
item=“id” : 每次循环的单个元素
open="(" : 集合元素开始用"("包括
separator="," : 每个元素用","分隔开
close=")" : 集合最后用")"来结尾
#{id} : 每次遍历元素的值
-
测试代码
@Test public void findByIds(){ List<Integer> list = new ArrayList<>( Arrays.asList( 1,2,3,4 ) ); List<Employee> employees = employeeMapper.findByIds( list ); for (Employee employee : employees) { System.out.println(employee); } }