<?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="com.lusifer.mybatis.dao.DynamicStudentDao"> <!-- if --> <select id="selectByIf" resultType="com.lusifer.mybatis.entity.Student"> SELECT id, name, age, score FROM student WHERE 1 = 1 <if test="name != null and name != ''"> AND name LIKE concat('%', #{name}, '%') </if> <if test="age != null and age > 0"> AND age > #{age} </if> </select> </mapper>
<!-- where--> <select id="selectByWhere" resultType="com.lusifer.mybatis.entity.Student"> SELECT id, name, age, score FROM student <where> <if test="name != null and name != ''"> AND name LIKE concat('%', #{name}, '%') </if> <if test="age != null and age > 0"> AND age > #{age} </if> </where> </select>
<!-- foreach --> <select id="selectByForeach" resultType="com.lusifer.mybatis.entity.Student"> <!-- select * from student where id in (2, 4) --> SELECT id, name, age, score FROM student <!--不能识别写,必须是array表示数组--> <if test="array != null and array.length > 0"> WHERE id IN <!--指定遍历集合类型为数组--> <foreach collection="array" open="(" close=")" item="id" separator=","> #{id} </foreach> </if> </select>
foreach 标签-遍历集合
遍历集合的方式与遍历数组的方式相同,只不过是将 array 替换成了 list
遍历泛型为基本类型的 List
定义 DAO 接口
1 2 3 4 5 6
/** * 使用 foreach 标签以 list 基本类型的形式查询 * @param ids * @return */ public List<Student> selectByForeachWithListBase(List<Long> ids);
定义映射文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<!-- foreach --> <select id="selectByForeachWithListBase" resultType="com.lusifer.mybatis.entity.Student"> <!-- select * from student where id in (2, 4) --> SELECT id, name, age, score FROM student <if test="list != null and list.size > 0"> WHERE id IN <foreach collection="list" open="(" close=")" item="id" separator=","> #{id} </foreach> </if> </select>
遍历泛型为自定义类型的 List
定义 DAO 接口
1 2 3 4 5 6
/** * 使用 foreach 标签以 list 自定义类型的形式查询 * @param students * @return */ public List<Student> selectByForeachWithListCustom(List<Student> students);
定义映射文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<!-- foreach --> <select id="selectByForeachWithListCustom" resultType="com.lusifer.mybatis.entity.Student"> <!-- select * from student where id in (2, 4) --> SELECT id, name, age, score FROM student <if test="list != null and list.size > 0"> WHERE id IN <foreach collection="list" open="(" close=")" item="student" separator=","> #{student.id} </foreach> </if> </select>
<sql id="select"> SELECT id, name, age, score FROM student </sql>
1 2 3 4 5 6 7 8 9 10 11 12
<!-- foreach --> <select id="selectByForeachWithListCustom" resultType="com.lusifer.mybatis.entity.Student"> <!-- select * from student where id in (2, 4) --> <include refid="select" />
<if test="list != null and list.size > 0"> WHERE id IN <foreach collection="list" open="(" close=")" item="student" separator=","> #{student.id} </foreach> </if> </select>