环境说明
- JDK 17
- MySQL 8.0.32
- Mybatis 3.5.10
环境准备
导入相关依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
动态SQL
if 标签
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。
<mapper namespace="StudentMapper">
<resultMap id="studentMap" type="com.test.entity.Student">
<id property="sid" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
</resultMap>
<select id="selectStudent" resultMap="studentMap">
select *
from student
where id > #{sid}
<if test="name != null">
and name like concat(#{name}, '%')
</if>
</select>
</mapper>
Student student = new Student();
student.setSid(2);
student.setName("Jaco");
List<Student> list = sqlSession.selectList("selectStudent", student);
list.forEach(System.out::println);
choose 标签
<mapper namespace="StudentMapper">
<resultMap id="studentMap" type="com.test.entity.Student">
<id property="sid" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
</resultMap>
<select id="selectStudent" resultMap="studentMap">
select *
from student
where id > #{sid}
<choose>
<when test="name != null">
and name like concat(#{name}, '%')
</when>
<when test="sex != null">
and sex like #{sex}
</when>
<otherwise>
and flag = 1
</otherwise>
</choose>
</select>
</mapper>
Student student = new Student();
student.setSid(2);
student.setName("Jaco");
student.setSex("女");
List<Student> list = sqlSession.selectList("selectStudent", student);
list.forEach(System.out::println);
trim标签
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<mapper namespace="StudentMapper">
<resultMap id="studentMap" type="com.test.entity.Student">
<id property="sid" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
</resultMap>
<select id="selectStudent" resultMap="studentMap">
select *
from student
<where>
<if test="sid != 0">
and id > #{sid}
</if>
<if test="name != null">
and name like concat(#{name}, '%')
</if>
</where>
</select>
</mapper>
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为(prefixOverrides 属性会忽略通过管道符分隔的文本序列(此处的空格是必要的)。该例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。):
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列(set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号):
<update id="updateStudent" parameterType="com.test.entity.Student">
update student
<set>
<if test="name != null">name=#{name},</if>
<if test="sex != null">sex=#{sex}</if>
</set>
where id=#{sid}
</update>
Student student = new Student();
student.setSid(8);
student.setName("Jacobo");
student.setSex("男");
sqlSession.update("updateStudent", student);
等效trim 标签:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
foreach标签
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。foreach 元素的功能非常强大,它允许你指定一个集合,item指代遍历到的单个元素(可以是属性或对象甚至是数组等),index指代元素的索引。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。
<mapper namespace="StudentMapper">
<resultMap id="studentMap" type="com.test.entity.Student">
<id property="sid" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
</resultMap>
<select id="selectStudent" resultMap="studentMap">
select *
from student
<where>
<foreach item="item" index="index" collection="list"
open="id in (" separator="," close=")">
#{item}
</foreach>
</where>
</select>
</mapper>
try(SqlSession sqlSession = SqlSessionUtil.openSession(true)){
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(10);
ids.add(null);
ids.add(3);
List<Student> list = sqlSession.selectList("selectStudent", ids);
list.forEach(System.out::println);
}
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
注解方式
注解方式下,使用动态SQL需要将sql语句包含在script标签里。在 内使用特殊符号,则使用java的转义字符,如 双引号 “” 使用单引号代替或者使用反斜杠转义:
public interface StudentMapper {
@Results({
@Result(column = "id", property = "sid"),
@Result(column = "name", property = "name"),
@Result(column = "sex", property = "sex")
})
@Select({"<script>",
"select * ",
"from student ",
"<where> ",
" <foreach item='item' index='index' collection='list' ",
" open='id in (' separator=',' close=')'> ",
" #{item} ",
" </foreach> ",
"</where>",
"</script>"})
List<Student> selectStudentList(List<Integer> list);
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(3);
ids.add(5);
ids.add(8);
ids.add(11);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> list = mapper.selectStudentList(ids);
list.forEach(System.out::println);