动态sql:sql内容是变化的,可以根据条件获取到不同的sql语句,主要用于解决查询条件不确定。主要是where部分发生变化。
实现:使用mybatis提供的标签,<if> <where> <foreach>
标签介绍
语法:<if test=”条件”> sql 语句的部分 </if>
<select id="selectStudentIf" resultType="com.liangwei.entity.Student">select id, name, email, age from studentwhere 1=1<if test="name != null and name != '' ">and name = #{name}</if><if test="age > 0">or age > #{age}</if></select>
where 1=1 这里是为了防止某些条件没有满足造成的sql语法错误
在有查询条件时, 可以自动添加上 where 子句;没有查询条件时,不会添加where 子句。需要注意的是,第一个
<select id="selectStudentIf" resultType="com.liangwei.entity.Student">select id, name, email, age from student<where><if test="name != null and name != '' ">and name = #{name}</if><if test="age > 0">or age > #{age}</if></where></select>
- collection 表示要遍历的集合类型, list , array 等。
open、 close、 separator 为对遍历内容的 SQL 拼接。
用法1:基本数据类型
/*** foreach标签用法1* @param idlist* @return*/List<Student> selectForeachOne(List<Integer> idlist);
<select id="selectForeachOne" resultType="com.liangwei.entity.Student">select id, name , email, age from student where id in<foreach collection="list" item="myid" open="(" close=")" separator=",">#{myid}</foreach></select>
collection:接口中方法参数的类型。
- 数组使用 array
- list集合使用list
- item:自定义的,表示数组和集合成员的变量
- open:循环开始时的字符
- close:循环结束时的字符
- separator:分割字符
用法2:对象
/*** foreach标签用法2* @param idlist* @return*/List<Student> selectForeachTwo(List<Student> stuList);
<select id="selectForeachTwo" resultType="com.liangwei.entity.Student">select id, name , email, age from student<if test="list != null and list.size() > 0">where id in<foreach collection="list" item="stuObject" open="(" close=")" separator=",">#{stuObject.id}</foreach></if></select>
代码片段
<sql id="studetnSql">select id, name, email, age from student</sql><select id="selectStudentSqlFragment" resultType="com.liangwei.entity.Student"><include refid="studentSql"/><if test="list != null and list.size() > 0">where id in<foreach collection="list" item="stuObject" open="(" close=")" separator=",">#{stuObject.id}</foreach></if></select>
