MyBatis动态SQL详解
MyBatis动态SQL详解
前置知识
在开始本教程之前,建议您已经完成:
- MyBatis基础入门教程
- MyBatis核心配置详解
- MyBatis增删改查操作
- MyBatis映射关系处理
- 了解SQL基础语法
什么是动态SQL?
MyBatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题。
动态SQL的优势
- 避免SQL注入:使用参数化查询
- 提高可维护性:SQL语句结构清晰
- 减少代码冗余:一个SQL语句处理多种情况
- 提高开发效率:减少手动拼接SQL的工作
if 标签
基础用法
if标签可通过test属性(即传递过来的数据)的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行。
// Mapper接口
List<Emp> getEmpByCondition(Emp emp);
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp where 1=1
<if test="empName != null and empName != ''">
and emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
</select>
测试代码
@Test
public void getEmpByCondition() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
// 测试不同条件组合
Emp emp1 = new Emp(null, "张三", null, null, null, null);
List<Emp> emps1 = mapper.getEmpByCondition(emp1);
System.out.println("按姓名查询: " + emps1);
Emp emp2 = new Emp(null, null, 23, "男", null, null);
List<Emp> emps2 = mapper.getEmpByCondition(emp2);
System.out.println("按年龄和性别查询: " + emps2);
}
恒成立条件说明
在where后面添加一个恒成立条件1=1
:
- 这个恒成立条件并不会影响查询的结果
- 这个
1=1
可以用来拼接and
语句 - 如果不加上恒成立条件,当第一个条件为null时,SQL语句会变成
select * from t_emp where and age = ?
,会报错
where 标签
基础用法
where和if一般结合使用:
- 若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
- 若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and/or去掉
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<where>
<if test="empName != null and empName != ''">
emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
</where>
</select>
where标签限制
where标签不能去掉条件后多余的and/or,只能去掉条件前面的and/or:
<!-- 这种用法是错误的,只能去掉条件前面的and/or,条件后面的不行 -->
<if test="empName != null and empName != ''">
emp_name = #{empName} and
</if>
<if test="age != null and age != ''">
age = #{age}
</if>
trim 标签
基础用法
trim用于去掉或添加标签中的内容,常用属性:
prefix
:在trim标签中的内容的前面添加某些内容suffix
:在trim标签中的内容的后面添加某些内容prefixOverrides
:在trim标签中的内容的前面去掉某些内容suffixOverrides
:在trim标签中的内容的后面去掉某些内容
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and|or">
<if test="empName != null and empName != ''">
emp_name = #{empName} and
</if>
<if test="age != null and age != ''">
age = #{age} and
</if>
<if test="sex != null and sex != ''">
sex = #{sex} or
</if>
<if test="email != null and email != ''">
email = #{email}
</if>
</trim>
</select>
测试结果
@Test
public void getEmpByCondition() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
Emp emp = new Emp(null, "张三", null, null, null, null);
List<Emp> emps = mapper.getEmpByCondition(emp);
System.out.println(emps);
}
执行结果:select * from t_emp where emp_name = ?
trim标签特点
若trim中的标签都不满足条件,则trim标签没有任何效果,也就是只剩下select * from t_emp
choose、when、otherwise 标签
基础用法
choose、when、otherwise
相当于if...else if..else
,when至少要有一个,otherwise至多只有一个。
<select id="getEmpByChoose" resultType="Emp">
select * from t_emp
<where>
<choose>
<when test="empName != null and empName != ''">
emp_name = #{empName}
</when>
<when test="age != null and age != ''">
age = #{age}
</when>
<when test="sex != null and sex != ''">
sex = #{sex}
</when>
<when test="email != null and email != ''">
email = #{email}
</when>
<otherwise>
did = 1
</otherwise>
</choose>
</where>
</select>
测试代码
@Test
public void getEmpByChoose() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
Emp emp = new Emp(null, "张三", 23, "男", "123@qq.com", null);
List<Emp> emps = mapper.getEmpByChoose(emp);
System.out.println(emps);
}
执行结果:只执行第一个满足的条件,相当于if a else if b else if c else d
foreach 标签
基础属性
collection
:设置要循环的数组或集合item
:表示集合或数组中的每一个数据separator
:设置循环体之间的分隔符,分隔符前后默认有一个空格,如,
open
:设置foreach标签中的内容的开始符close
:设置foreach标签中的内容的结束符
批量删除
// Mapper接口
int deleteMoreByArray(Integer[] eids);
<delete id="deleteMoreByArray">
delete from t_emp where eid in
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
@Test
public void deleteMoreByArray() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
int result = mapper.deleteMoreByArray(new Integer[]{6, 7, 8, 9});
System.out.println(result);
}
执行结果:delete from t_emp where eid in (6, 7, 8, 9)
批量添加
// Mapper接口
int insertMoreByList(@Param("emps") List<Emp> emps);
<insert id="insertMoreByList">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
</foreach>
</insert>
@Test
public void insertMoreByList() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
Emp emp1 = new Emp(null, "a", 1, "男", "123@321.com", null);
Emp emp2 = new Emp(null, "b", 1, "男", "123@321.com", null);
Emp emp3 = new Emp(null, "c", 1, "男", "123@321.com", null);
List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
int result = mapper.insertMoreByList(emps);
System.out.println(result);
}
执行结果:insert into t_emp values (null,?,?,?,?,null),(null,?,?,?,?,null),(null,?,?,?,?,null)
SQL 片段
基础用法
sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入。
声明sql片段
<sql id="empColumns">eid,emp_name,age,sex,email</sql>
引用sql片段
<select id="getEmpByCondition" resultType="Emp">
select <include refid="empColumns"></include> from t_emp
</select>
带参数的SQL片段
<!-- 声明带参数的SQL片段 -->
<sql id="empColumnsWithTable">
${tableName}.eid,${tableName}.emp_name,${tableName}.age,${tableName}.sex,${tableName}.email
</sql>
<!-- 使用带参数的SQL片段 -->
<select id="getEmpByCondition" resultType="Emp">
select <include refid="empColumnsWithTable">
<property name="tableName" value="t_emp"/>
</include> from t_emp
</select>
动态SQL最佳实践
1. 合理使用标签组合
<!-- 推荐:使用where + if组合 -->
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<where>
<if test="empName != null and empName != ''">
emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
</where>
</select>
2. 避免SQL注入
<!-- 错误:使用${}进行字符串拼接 -->
<select id="getEmpByLike" resultType="Emp">
select * from t_emp where emp_name like '%${empName}%'
</select>
<!-- 正确:使用#{}进行参数化查询 -->
<select id="getEmpByLike" resultType="Emp">
select * from t_emp where emp_name like concat('%',#{empName},'%')
</select>
3. 使用SQL片段提高复用性
<!-- 定义常用的查询字段 -->
<sql id="Base_Column_List">
eid, emp_name, age, sex, email, did
</sql>
<!-- 在多个查询中复用 -->
<select id="getEmpById" resultType="Emp">
select <include refid="Base_Column_List"/> from t_emp where eid = #{eid}
</select>
<select id="getEmpList" resultType="Emp">
select <include refid="Base_Column_List"/> from t_emp
</select>
4. 批量操作优化
<!-- 批量插入优化 -->
<insert id="batchInsert" parameterType="java.util.List">
insert into t_emp (emp_name, age, sex, email, did) values
<foreach collection="list" item="emp" separator=",">
(#{emp.empName}, #{emp.age}, #{emp.sex}, #{emp.email}, #{emp.did})
</foreach>
</insert>
<!-- 批量更新优化 -->
<update id="batchUpdate" parameterType="java.util.List">
<foreach collection="list" item="emp" separator=";">
update t_emp
set emp_name = #{emp.empName}, age = #{emp.age}
where eid = #{emp.eid}
</foreach>
</update>
复杂动态SQL示例
多条件组合查询
// Mapper接口
List<Emp> getEmpByComplexCondition(@Param("emp") Emp emp,
@Param("minAge") Integer minAge,
@Param("maxAge") Integer maxAge,
@Param("deptIds") List<Integer> deptIds);
<select id="getEmpByComplexCondition" resultType="Emp">
select * from t_emp
<where>
<!-- 基础条件 -->
<if test="emp.empName != null and emp.empName != ''">
and emp_name like concat('%', #{emp.empName}, '%')
</if>
<if test="emp.sex != null and emp.sex != ''">
and sex = #{emp.sex}
</if>
<!-- 年龄范围查询 -->
<if test="minAge != null">
and age >= #{minAge}
</if>
<if test="maxAge != null">
and age <= #{maxAge}
</if>
<!-- 部门ID列表查询 -->
<if test="deptIds != null and deptIds.size() > 0">
and did in
<foreach collection="deptIds" item="deptId" open="(" separator="," close=")">
#{deptId}
</foreach>
</if>
</where>
order by eid desc
</select>
动态排序
// Mapper接口
List<Emp> getEmpListWithOrder(@Param("orderBy") String orderBy, @Param("orderType") String orderType);
<select id="getEmpListWithOrder" resultType="Emp">
select * from t_emp
<choose>
<when test="orderBy != null and orderBy != ''">
order by
<choose>
<when test="orderBy == 'name'">emp_name</when>
<when test="orderBy == 'age'">age</when>
<when test="orderBy == 'id'">eid</when>
<otherwise>eid</otherwise>
</choose>
<choose>
<when test="orderType == 'desc'">desc</when>
<otherwise>asc</otherwise>
</choose>
</when>
<otherwise>
order by eid asc
</otherwise>
</choose>
</select>
总结
本教程详细介绍了MyBatis的动态SQL技术,包括:
- ✅ if标签:条件判断和SQL拼接
- ✅ where标签:自动处理where关键字和and/or
- ✅ trim标签:精确控制SQL片段的前后缀
- ✅ choose标签:多条件选择逻辑
- ✅ foreach标签:批量操作和集合遍历
- ✅ SQL片段:代码复用和维护性提升
- ✅ 最佳实践:安全性和性能优化
下一步学习
- 学习MyBatis的缓存机制
- 了解一级缓存和二级缓存
- 掌握第三方缓存集成
在下一篇文章中,我们将学习MyBatis的缓存机制,包括一级缓存、二级缓存、缓存配置和第三方缓存集成等高级特性。