动态SQL是 MyBatis 中非常强大且灵活的功能,允许你根据不同的条件构建SQL查询。
这主要通过 <if>、<choose>、<when>、<otherwise>、<foreach>等标签实现。
查询场景
| |
| |
| |
| |
| |
| List<Emp> getEmpCondition(Emp emp); |
if标签的使用
<if> 标签:该标签用于根据条件判断是否包含某段SQL片段。
| <select id="getEmpCondition" resultType="com.evan.mybatis.entity.Emp"> |
| select * from t_emp where 1=1 |
| <if test="empName != null and empName != ''"> |
| and emp_name = |
| </if> |
| <if test="age != null and age != ''"> |
| and age = |
| </if> |
| <if test="gender != null and gender != ''"> |
| and gender = |
| </if> |
| </select> |
测试
| @Test |
| public void test1() { |
| SqlSession sqlSession = SqlSessionUtil.getSqlSession(); |
| EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); |
| Emp emp = new Emp(); |
| emp.setEmpName("李四"); |
| List<Emp> emps = mapper.getEmpCondition(emp); |
| emps.forEach(System.out::println); |
| sqlSession.close(); |
| } |
结论:if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行
where标签的使用
- 若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
- 若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件前面多余的and或or去掉
注意:where标签会自动去掉条件前面多余的and或or
| <select id="getEmpCondition" resultType="com.evan.mybatis.entity.Emp"> |
| select * from t_emp |
| <where> |
| <if test="empName != null and empName !=''"> |
| and emp_name = |
| </if> |
| <if test="age != null and age != ''"> |
| and age = |
| </if> |
| <if test="gender != null and gender !=''"> |
| or gender = |
| </if> |
| </where> |
| </select> |
测试
| @Test |
| public void test1() { |
| SqlSession sqlSession = SqlSessionUtil.getSqlSession(); |
| EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); |
| Emp emp = new Emp(); |
| emp.setEmpName("李四"); |
| emp.setAge(19); |
| emp.setGender("女"); |
| List<Emp> emps = mapper.getEmpCondition(emp); |
| emps.forEach(System.out::println); |
| sqlSession.close(); |
| } |
trim标签的使用
trim用于去掉或添加标签中的内容,常用属性:
- prefix:在trim标签中内容的前面添加指定内容
- prefixOverrides:在trim标签中内容的前面去掉指定内容
- suffix:在trim标签中内容的后面添加指定内容
- suffixOverrides:在trim标签中内容的后面去掉指定内容
| <select id="getEmpCondition" resultType="com.evan.mybatis.entity.Emp"> |
| select * from t_emp |
| <trim prefix="where" suffixOverrides="and|or"> |
| <if test="empName != null and empName != ''"> |
| emp_name = |
| </if> |
| <if test="age != null and age != ''"> |
| age = |
| </if> |
| <if test="gender != null and gender != ''"> |
| gender = |
| </if> |
| </trim> |
| </select> |
测试
| @Test |
| public void test1() { |
| SqlSession sqlSession = SqlSessionUtil.getSqlSession(); |
| EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); |
| Emp emp = new Emp(0,"李四",19,"男",null); |
| List<Emp> emps = mapper.getEmpCondition(emp); |
| emps.forEach(System.out::println); |
| sqlSession.close(); |
| } |
choose、when、otherwise标签的使用
<choose>、<when>、<otherwise> 标签:这些标签类似于Java中的switch-case-default结构。
<choose>标签中的<when>标签表达式结果满足则条件拼接查询,否则在读多个<when>标签中继续判断,如都不满足,则执行<otherwise>标签内容。
注意:when至少有一个,otherwise最多设置一个
| <select id="getEmpCondition" resultType="com.evan.mybatis.entity.Emp"> |
| select * from t_emp |
| <where> |
| <choose> |
| <when test="empName != null and empName != ''"> |
| emp_name = |
| </when> |
| <when test="age != null and age != ''"> |
| age = |
| </when> |
| <when test="gender != null and gender != ''"> |
| gender = |
| </when> |
| <otherwise> |
| gender = '女' |
| </otherwise> |
| </choose> |
| </where> |
| </select> |
测试
| @Test |
| public void test1() { |
| SqlSession sqlSession = SqlSessionUtil.getSqlSession(); |
| EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); |
| Emp emp = new Emp(0,null,0,"男",null); |
| List<Emp> emps = mapper.getEmpCondition(emp); |
| emps.forEach(System.out::println); |
| sqlSession.close(); |
| } |
foreach标签的使用
场景1
方法形参为集合,实现批量添加操作。
| |
| |
| |
| |
| |
| int addEmp(@Param("emps") List<Emp> emps); |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| <insert id="addEmp"> |
| insert into t_emp(emp_name,age,gender,dept_id) values |
| <foreach collection="emps" item="e" open="values" separator="," index="myIndex"> |
| |
| (#{e.empName},#{e.age},#{e.gender},null) |
| </foreach> |
| </insert> |
测试
| @Test |
| public void test2() { |
| SqlSession sqlSession = SqlSessionUtil.getSqlSession(); |
| EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); |
| Emp emp1 = new Emp(0, "evan", 22, "女", null); |
| Emp emp2 = new Emp(0, "allen", 23, "男", null); |
| Emp emp3 = new Emp(0, "john", 24, "女", null); |
| int result = mapper.addEmp(Arrays.asList(emp1, emp2, emp3)); |
| System.out.println("结果:" + result); |
| sqlSession.close(); |
| } |
场景2
形参为List集合,实现批量更新操作。
| |
| |
| |
| |
| |
| Integer updateUserBatch(@Param("users") List<User> users); |
| <update id="updateUserBatch" parameterType="User"> |
| <foreach collection="users" item="u" separator=";"> |
| update t_user |
| <set> |
| username = |
| </set> |
| <where> |
| id = |
| </where> |
| </foreach> |
| </update> |
或
| <update id="updateEmpBatch" parameterType="Emp"> |
| <foreach collection="emps" item="e" separator=";"> |
| update t_emp set emp_name= |
| </foreach> |
| </update> |
测试
| @Test |
| public void test5() { |
| EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); |
| Emp emp1 = new User(90, "华华", "890", 10, "男", "hh@sian.com"); |
| Emp emp2 = new User(91, "睇睇", "890", 10, "男", "hh@sian.com"); |
| Emp emp3 = new User(92, "倩倩", "890", 10, "男", "hh@sian.com"); |
| List<Emp> list = Arrays.asList(emp1, emp2, emp3); |
| Integer result = mapper.updateEmpBatch(list); |
| System.out.println(result); |
| } |
批量更新时需要注意
上面批量插入的例子本质上是一条SQL语句,而实现批量更新则需要多条SQL语句拼起来,用分号分开。也就是一次性发送多条SQL语句让数据库执行。此时需要在数据库连接信息的URL地址中设置:
jdbc.url=jdbc:mysql:///mybatis-example?allowMultiQueries=true
例如:
| jdbc.url=jdbc:mysql://localhost:3306/dbtest1?useUnicode=true |
| &characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8 |
| &allowMultiQueries=true |
关于foreach标签的collection属性
如果没有给接口中List类型的参数使用@Param
注解指定一个具体的名字,那么在collection属性中默认可以使用collection或list来引用这个list集合。这一点可以通过异常信息看出来:
| Parameter 'emps' not found. Available parameters are [arg0, collection, list] |
在实际开发中,为了避免隐晦的表达造成一定的误会,建议使用@Param
注解明确声明变量的名称,然后在foreach标签的collection属性中按照@Param
注解指定的名称来引用传入的参数。
场景3
形参为数组,实现批量删除操作。
| |
| |
| |
| |
| |
| int removeEmp(@Param("empNames") String[] empNames); |
- 方式1: 通过形参数组并且where条件为in()方式条件进行批量删除
| <delete id="removeEmp"> |
| delete from t_emp where emp_name in |
| ( |
| <foreach collection="empNames" item="e" separator=","> |
| #{e} |
| </foreach> |
| ) |
| </delete> |
或
| <delete id="removeEmp"> |
| delete from t_emp where emp_name in |
| <foreach collection="empNames" separator="," item="e" open="(" close=")"> |
| |
| </foreach> |
| </delete> |
- 方式2: 通过形参数组并且where条件为or方式的模糊条件遍历
| <delete id="removeEmp" parameterType="java.lang.String"> |
| delete from t_emp |
| <where> |
| <foreach collection="empNames" item="e" separator="or"> |
| emp_name like '%${e}%' |
| </foreach> |
| </where> |
| </delete> |
测试
| @Test |
| public void test3() { |
| SqlSession sqlSession = SqlSessionUtil.getSqlSession(); |
| EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); |
| String[] args = { |
| "evan", |
| "allen", |
| "john"}; |
| int result = mapper.removeEmp(args); |
| System.out.println("结果:" + result); |
| sqlSession.close(); |
| } |
sql标签的使用
sql标签,可以记录一段公共sql片段,在使用的地方通过include标签进行引入。
| |
| <sql id="empColumns">emp_id,emp_name,age,gender,dept_id</sql> |
| |
| <select id="getEmpCondition" resultType="com.evan.mybatis.entity.Emp"> |
| select <include refid="empColumns"/> 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="gender != null and gender != ''"> |
| gender = #{gender} |
| </when> |
| <otherwise> |
| gender = '女' |
| </otherwise> |
| </choose> |
| </where> |
| </select> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南