动态sql语句主要为以下语句
1、动态SQL:if 语句
2、动态SQL:if+where 语句
3、动态SQL:if+set 语句
4、动态SQL:choose(when,otherwise) 语句
5、动态SQL:trim 语句
6、动态SQL: SQL 片段
7、动态SQL: foreach 语句
之前的几篇学习博客我用mybatis对一张表进行的CRUD操作,但是 SQL 语句都比较简单,如果有比较复杂的 SQL 语句,经常需要拼接,而拼接 SQL稍微不注意就容易出错此时我们可以用mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签来解决这个问题,这几个标签可组合成非常灵活的SQL语句,用起来也是很舒服
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 <!-- namespace:表示名称空间。现在的目的是区分id的. --> 5 <mapper namespace="com.zhiyou100.zhl.dao.UsersDao"> 6 <sql id="detail"> 7 id,name,age,sex,day 8 </sql> 9 10 <select id="selByWhere" resultType="com.zhiyou100.zhl.bean.Users"> 11 select * from users 12 <where> 13 <if test="name!=null"> 14 and name=#{name} 15 </if> 16 <if test="sex!=null and sex!=''"> 17 and sex=#{sex} 18 </if> 19 </where> 20 </select> 21 22 <update id="updateWhere"> 23 update users 24 <set> 25 <if test="name!=null"> 26 name=#{name}, 27 </if> 28 <if test="sex!=null"> 29 sex=#{sex}, 30 </if> 31 <if test="age>0"> 32 age=#{age}, 33 </if> 34 <if test="day!=null"> 35 day=#{day} 36 </if> 37 </set> 38 where id=#{id} 39 </update> 40 41 <select id="selByWhere2" resultType="com.zhiyou100.zhl.bean.Users"> 42 select 43 <include refid="detail"/> 44 from users 45 <where> 46 <choose> 47 <when test="name!=null and name!=''"> 48 name like concat('%',#{name},'%') 49 </when> 50 <when test="sex!=null and sex!=''"> 51 sex=#{sex} 52 </when> 53 <otherwise> 54 age>=#{age} 55 </otherwise> 56 </choose> 57 </where> 58 </select> 59 60 <select id="selByWhere3" resultType="com.zhiyou100.zhl.bean.Users"> 61 select 62 <include refid="detail"/> 63 from users 64 <trim prefix="where" prefixOverrides="and | or"> 65 <if test="name!=null and name!=''"> 66 and name=#{name} 67 </if> 68 <if test="sex!=null and sex!=''"> 69 and sex=#{sex} 70 </if> 71 <if test="age>0"> 72 and age=#{age} 73 </if> 74 <if test="day!=null and day!=''"> 75 and day=#{day} 76 </if> 77 </trim> 78 </select> 79 80 <update id="updateWhere2"> 81 update users 82 <trim prefix="set" suffixOverrides=","> 83 <if test="name!=null"> 84 name=#{name}, 85 </if> 86 <if test="sex!=null"> 87 sex=#{sex}, 88 </if> 89 <if test="age>0"> 90 age=#{age}, 91 </if> 92 <if test="day!=null"> 93 day=#{day} 94 </if> 95 </trim> 96 where id=#{id} 97 </update> 98 99 <delete id="deleteByIds"> 100 delete from users 101 <where> 102 <foreach collection="ids" open="id in(" close=")" separator="," item="id"> 103 #{id} 104 </foreach> 105 </where> 106 </delete> 107 108 109 <delete id="deleteByIds2"> 110 delete from users where id in 111 <foreach collection="ids" open="(" close=")" separator="," item="id"> 112 #{id} 113 </foreach> 114 </delete> 115 116 117 </mapper>