官网
https://mybatis.org/mybatis-3/zh/dynamic-sql.html
动态sql之if
概念
If标签用于条件判断,当条件成立就附加<if></if>之间的sql语句,如果条件不成立就不附加<if></if>之间的sql语句。
<if test=”xxx”> ......</if>
<select id="getPersonByCodition" parameterType="Person" resultType="Person">
select * from emp where 1=1
<if test="ENAME!=null">
and ENAME=#{ENAME}
</if>
<if test="JOB!=null">
and JOB=#{JOB}
</if>
<if test="DEPTNO!=null">
and DEPTNO=#{DEPTNO}
</if>
动态sql之where标签
概念
<where>标签在sql语句后面附加where关键字,当where 标签中有成条件成立时就会附加where关键字,如where标签中没有任何条件成立则不会附加where关键字,where会忽略掉离他最近的一个无关的and 或or\
动态sql之choose、when、otherwises标签
概念
当choose中有一个when成立就附加该条件,其它的when都不会被执行,如果所有的when都不成立就附加otherwise标签之间的sql语句
<select id="getPersonByCodition" resultType="Person">
select * from emp
<where>
<choose>
<when test="ENAME!=null">
and ENAME=#{ENAME}
</when>
<when test="DEPTNO!=null">
and DEPTNO=#{DEPTNO}
</when>
<otherwise>
and 1=1
</otherwise>
</choose>
</where>
</select>
动态sql之set标签
概念
Set标签用于更新,当set标签中有if条成立成就会附加该列,更新指定的列。会自动忽略掉最后一个与sql语句无关的逗号。
<select id="updatePerson" >
update emp
<set>
<if test="ENAME!=null">
ENAME=#{ENAME},
</if><if test="DEPTNO!=null">
DEPTNO=#{DEPTNO},
</if>
<if test="MGR!=null">
MGR=#{MGR},
</if>
<if test="JOB!=null">
JOB=#{JOB},
</if>
</set>
</select>
动态sql之foreach标签
概念
Collection: 指定集合的类型
Item: 定义一个变量用来接收集合中每个对象
Separator: 分隔符,当本次循环结束后,下次循环开始前附加分隔符
Open 附加字符 ,在循环开始前,附加字符串
Close 附加字符 ,在循环结束后,附加字符串
Index 集合的索引
批量添加,删除 修改
<insert id="addPersons" parameterType="list" useGeneratedKeys="true" keyProperty="EMPNO">
insert into emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values
<foreach collection="list" item="Person" separator="," open="(" close=")">
#{Person.EMPNO},#{Person.ENAME},#{Person.JOB},#{Person.MGR},#{Person.HIREDATE},#{Person.SAL},#{Person.COMM},#{Person.DEPTNO}
</foreach>
</insert>
动态sql之bind标签
拼装数据库 keyword 查找的关键字的字符串
<select id="getPersonBylikeName" resultType="Person">
<bind name="keyWord" value="'%'+ _parameter.getENAME()+'%'" ></bind>
select * from emp where ENAME like #{keyWord}
</select>