文章目录

  • 前言
  • 一、if元素
  • 二、where元素
  • 三、trim元素
  • 1. trim作用
  • 2.trim处理流程
  • 四、choose/when/otherwise元素
  • 五、set元素
  • 六、foreach元素
  • 1.案例:in多值查询
  • 2.案例:MYSQL批量插入
  • 3.案例:oracle批量插入
  • 4.内置参数
  • 七、bind绑定和sql片段
  • 1、bind
  • 2、sql/include元素


前言

动态 SQL是MyBatis强大特性之一。极大的简化我们拼装SQL的操作。
动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似。
MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作:
if 、 choose (when, otherwise)、trim (where, set)、 foreach

一、if元素

if test="判断表达式(OGNL)">需要追加的sql</if>
 <select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee where
		 	<!-- test:判断表达式(OGNL)
		 	OGNL参照PPT或者官方文档。
		 	  	 c:if  test
		 	从参数中取值进行判断
		 	遇见特殊符号应该去写转义字符:
		 	&&:&&
		 	-->
		 	<if test="id!=null">
		 		and id=#{id}
		 	</if>
		 	<if test="lastName!=null && lastName!=""">
		 		and last_name like #{lastName}
		 	</if>
		 	<if test="email!=null and email.trim()!=""">
		 		and email=#{email}
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	</if>
	 </select>

if中的 test从参数中取值进行判断,test的值为一个判断表达式,写法上采用OGNL表达式的方式。
遇见特殊符号应该去写转义字符:&& 转义字符链接

二、where元素

上面案例不传参数后where后面会多一个AND符号?
第一种:mybatis中已经考虑到这种问题了,属于通用性的问题,mybatis中通过where 元素来解决,当使用where元素的时候,mybatis会将where内部拼接的sql进行处理,会将这部分sql前面的AND 或者 OR给去掉,并在前面追加一个where
第二种: where 1=1 在后面拼接sql就行

<select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<!-- where -->
	 	<where>
		 	<!-- test:判断表达式(OGNL)
		 	OGNL参照PPT或者官方文档。
		 	  	 c:if  test
		 	从参数中取值进行判断
		 	
		 	遇见特殊符号应该去写转义字符:
		 	&&:&&
		 	-->
		 	<if test="id!=null">
		 		id=#{id}
		 	</if>
		 	<if test="lastName!=null && lastName!=""">
		 		and last_name like #{lastName}
		 	</if>
		 	<if test="email!=null and email.trim()!=""">
		 		and email=#{email}
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	</if>
	 	</where>
	 </select>

三、trim元素

1. trim作用

自定义标签体类的字符的截取规则

2.trim处理流程

trim元素内部可以包含各种动态sql,如where、chose、sql等各种元素,使用trim包含的元素,mybatis处理过程:
1.先对trim内部的sql进行拼接,比如这部分sql叫做sql1
2.将sql1字符串前面的部分中包含trim的prefixOverrides指定的部分给去掉,得到sql2
3.将sql2字符串后面的部分中包含trim的suffixOverrides指定的部分给去掉,得到sql3
4.在sql3前面追加trim中prefix指定的值,得到sql4
5.在sql4后面追加trim中suffix指定的值,得到最终需要拼接的sql5

<select id="getEmpsByConditionTrim" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<!-- 后面多出的and或者or where标签不能解决 
	 	trim标签体中是整个字符串拼串后的结果
	 	prefix="":前缀:prefix给拼串后的整个字符串加一个前缀 
	 	prefixOverrides="":
	 			前缀覆盖: 去掉整个字符串前面多余的字符
	 	suffix="":后缀
	 			suffix给拼串后的整个字符串加一个后缀 
	 	suffixOverrides=""
	 			后缀覆盖:去掉整个字符串后面多余的字符
	 	-->
	 	<!-- 自定义字符串的截取规则 -->
	 	<trim prefix="where" suffixOverrides="and">
	 		<if test="id!=null">
		 		id=#{id} and
		 	</if>
		 	<if test="lastName!=null && lastName!=""">
		 		last_name like #{lastName} and
		 	</if>
		 	<if test="email!=null and email.trim()!=""">
		 		email=#{email} and
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	gender=#{gender}
		 	</if>
		 </trim>
	 </select>

注意上面的prefixOverrides的值的写法,如果有多个需要覆盖的之间用|进行分割,suffixOverrides写法和prefixOverrides的写法类似。

四、choose/when/otherwise元素

choose分支选择
这个相当于java中的if…else if…else和switch-case语法:

<choose>
    <when test="条件1">
        满足条件1追加的sql
    </when>
    <when test="条件2">
        满足条件2追加的sql
    </when>
    <when test="条件n">
        满足条件n追加的sql
    </when>
    <otherwise>
        都不满足追加的sql
    </otherwise>
</choose>

案例:

<select id="getEmpsByConditionChoose" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee 
	 	<where>
	 		<!-- 如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个 -->
	 		<choose>
	 			<when test="id!=null">
	 				id=#{id}
	 			</when>
	 			<when test="lastName!=null">
	 				last_name like #{lastName}
	 			</when>
	 			<when test="email!=null">
	 				email = #{email}
	 			</when>
	 			<otherwise>
	 				gender = 0
	 			</otherwise>
	 		</choose>
	 	</where>
	 </select>

注意:
choose内部的条件满足一个,choose内部的sql拼接就会结束。
otherwise属于可选的,当所有条件都不满足的时候,otherwise就会起作用。

五、set元素

trim 字符串截取(where(封装查询条件), set(封装修改条件))

<update id="updateEmp">
        <!-- Set标签的使用 -->
        update tbl_employee
        <set>
            <if test="lastName!=null">
                last_name=#{lastName},
            </if>
            <if test="email!=null">
                email=#{email},
            </if>
            <if test="gender!=null">
                gender=#{gender}
            </if>
        </set>
        where id=#{id}
        <!--  Trim:更新拼串
          update tbl_employee
          <trim prefix="set" suffixOverrides=",">
              <if test="lastName!=null">
                  last_name=#{lastName},
              </if>
              <if test="email!=null">
                  email=#{email},
              </if>
              <if test="gender!=null">
                  gender=#{gender}
              </if>
          </trim>
          where id=#{id}-->
</update>

六、foreach元素

相当于java中的循环,可以用来遍历数组、集合、map等。
语法

<foreach collection="需要遍历的集合" item="集合中当前元素" index="" open="" separator="每次遍历的分隔符" close="">
动态sql部分
</foreach>

collection:可以是一个List、Set、Map或者数组
item:集合中的当前元素的引用
index:用来访问当前元素在集合中的位置
separator:各个元素之间的分隔符
open和close:用来配置最后用什么前缀和后缀将foreach内部所有拼接的sql给包装起来。

1.案例:in多值查询

在SQL语法中如果我们想使用in的话直接可以像如下一样使用:

select * from HealthCoupon where useType in ( '4' , '3' )

但是如果在MyBatis中的使用in的话,像如下去做的话,肯定会报错:

Map<String, Object> selectByUserId(@Param("useType") String useType)
	
    <select id="selectByUserId" resultMap="BaseResultMap" parameterType="java.lang.String">
		select * from HealthCoupon where useType in (#{useType,jdbcType=VARCHAR})
    </select>

其中useType=“2,3”;这样的写法,看似很简单,但是MyBatis不支持这样操作,可以用$进行替换,如下方式即可运行

Map<String, Object> selectByUserId(@Param("useType") String useType)
	
    <select id="selectByUserId" resultMap="BaseResultMap" parameterType="java.lang.String">
		select * from HealthCoupon where useType in (${useType,jdbcType=VARCHAR})
    </select>

注意: #方式能够很大程度防止sql注入,$方式无法防止sql注入,所以还是推荐使用#方式,参考以下三种方式。

MyBatis中提供了foreach语句实现IN查询,foreach语法如下:

<!--
	collection:指定要遍历的集合:
	collection属性的参数类型可以使:List、数组、map集合
    collection: 必须跟mapper.java中@Param标签指定的元素名一样
    item: 表示在迭代过程中每一个元素的别名,可以随便起名,但是必须跟元素中的#{}里面的名称一样。item:将当前遍历出的元素赋值给指定的变量
	list类型的参数会特殊处理封装在map中,map的key就叫list
	separator:每个元素之间的分隔符
	open:遍历出所有结果拼接一个开始的字符
	close:遍历出所有结果拼接一个结束的字符
	index:索引。遍历list的时候是index就是索引,item就是当前值
	遍历map的时候index表示的就是map的key,item就是map的值
	#{变量名}就能取出变量的值也就是当前遍历出的元素
-->
<!--public List<Employee> getEmpByIn(@Param("ids") List<Integer> ids);-->
<select id="getEmpByIn" parameterType="java.util.List" resultType="com.ming.po.Employee">
    select * from tbl_employee
    <where>
        <if test="ids!=null and ids.size()>1">
            <foreach collection="ids" item="id" open="id in (" close=")" separator=",">
                #{id}
            </foreach>
        </if>
    </where>
</select>

正确的写法有以下几种写法:

如果参数的类型是List, 则在使用时,collection属性要必须指定为 list

List<User> selectByIdSet(List idList);
 
<select id="selectByIdSet" resultMap="BaseResultMap">
	SELECT
	<include refid="Base_Column_List" />
	from t_user
	WHERE id IN
	<foreach collection="list" item="id" index="index" open="(" close=")" separator=",">
	  #{id}
	</foreach>
</select>

如果参数的类型是Array,则在使用时,collection属性要必须指定为 array

List<User> selectByIdSet(String[] idList);
 
<select id="selectByIdSet" resultMap="BaseResultMap">
	SELECT
	<include refid="Base_Column_List" />
	from t_user
	WHERE id IN
	<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
	  #{id}
	</foreach>
</select>

参数有多个时
当查询的参数有多个时,有两种方式可以实现,一种是使用@Param(“xxx”)进行参数绑定,另一种可以通过Map来传参数。

@Param(“xxx”)方式如下:

List<User> selectByIdSet(@Param("name")String name, @Param("ids")String[] idList);
 
<select id="selectByIdSet" resultMap="BaseResultMap">
	SELECT
	<include refid="Base_Column_List" />
	from t_user
	WHERE  name=#{name,jdbcType=VARCHAR} and id IN
	<foreach collection="ids" item="id" index="index"
			 open="(" close=")" separator=",">
	  #{id}
	</foreach>
</select>

Map方式

Map<String, Object> params = new HashMap<String, Object>(2);
params.put("name", name);
params.put("idList", ids);
mapper.selectByIdSet(params);
 
<select id="selectByIdSet" resultMap="BaseResultMap">  
     select  
     <include refid="Base_Column_List" />  
     from t_user where 
     name = #{name}
     and ID in  
     <foreach item="item" index="index" collection="idList" open="(" separator="," close=")">  
      #{item}  
     </foreach>  
</select>

2.案例:MYSQL批量插入

方式一

<!-- 批量保存 -->
	 <!--public void addEmps(@Param("emps")List<Employee> emps);  -->
	 <!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
	<insert id="addEmps">
	 	insert into tbl_employee(
	 		<include refid="insertColumn"></include>
	 	) 
		values
		<foreach collection="emps" item="emp" separator=",">
			(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
		</foreach>
	 </insert>

方式二:allowMultiQueries=true;这种分号分隔多个sql可以用于其他的批量操作(删除,修改)

<!-- 这种方式需要数据库连接属性allowMultiQueries=true;
	 	这种分号分隔多个sql可以用于其他的批量操作(删除,修改) -->
	 <insert id="addEmps">
	 	<foreach collection="emps" item="emp" separator=";">
	 		insert into tbl_employee(last_name,email,gender,d_id)
	 		values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
	 	</foreach>
	 </insert>

添加jdbc.url=jdbc:mysql://localhost:3307/mybatis?allowMultiQueries=true

3.案例:oracle批量插入

<!-- Oracle数据库批量保存: 
	 	Oracle不支持values(),(),()
	 	Oracle支持的批量方式
	 	1、多个insert放在begin - end里面
	 		begin
			    insert into employees(employee_id,last_name,email) 
			    values(employees_seq.nextval,'test_001','test_001@atguigu.com');
			    insert into employees(employee_id,last_name,email) 
			    values(employees_seq.nextval,'test_002','test_002@atguigu.com');
			end;
		2、利用中间表:
			insert into employees(employee_id,last_name,email)
		       select employees_seq.nextval,lastName,email from(
		              select 'test_a_01' lastName,'test_a_e01' email from dual
		              union
		              select 'test_a_02' lastName,'test_a_e02' email from dual
		              union
		              select 'test_a_03' lastName,'test_a_e03' email from dual
		       )	
	 -->
	 <insert id="addEmps" databaseId="oracle">
	 	<!-- oracle第一种批量方式 -->
	 	<!-- <foreach collection="emps" item="emp" open="begin" close="end;">
	 		insert into employees(employee_id,last_name,email) 
			    values(employees_seq.nextval,#{emp.lastName},#{emp.email});
	 	</foreach> -->
	 	
	 	<!-- oracle第二种批量方式  -->
	 	insert into employees(
	 		<!-- 引用外部定义的sql -->
	 		<include refid="insertColumn">
	 			<property name="testColomn" value="abc"/>
	 		</include>
	 	)
	 			<foreach collection="emps" item="emp" separator="union"
	 				open="select employees_seq.nextval,lastName,email from("
	 				close=")">
	 				select #{emp.lastName} lastName,#{emp.email} email from dual
	 			</foreach>
	 </insert>

		

    <!--批量插入-->
    <resultMap id="roleDeptResultMap" type="com.yb.code.entity.system.RoleDept">
        <id property="id" column="ID"/>
        <result property="deptId" column="DEPT_ID"/>
        <result property="roleId" column="ROLE_ID"/>
        <result property="createTime" column="CREATE_TIME"/>
        <result property="createBy" column="CREATE_BY"/>
    </resultMap>

    <insert id="batchInsertRoleDept" parameterType="java.util.List" useGeneratedKeys="false">
        INSERT INTO P_SYS_ROLE_DEPT(ID,DEPT_ID,ROLE_ID)
        <foreach item="item" index="index" separator="union all" collection="list">
            SELECT
            #{item.id},
            #{item.deptId},
            #{item.roleId}
            FROM DUAL
        </foreach>
    </insert>

    <delete id="batchDeleteRoleDept" parameterType="java.lang.String">
        delete from P_SYS_ROLE_DEPT where ROLE_ID in
        <foreach collection="array" item="roleId" open="(" separator="," close=")">
            #{roleId}
        </foreach>
    </delete>

4.内置参数

<!-- 两个内置参数:
	 	不只是方法传递过来的参数可以被用来判断,取值。。。
	 	mybatis默认还有两个内置参数:
	 	_parameter:代表整个参数
	 		单个参数:_parameter就是这个参数
	 		多个参数:参数会被封装为一个map;_parameter就是代表这个map
	 	
	 	_databaseId:如果配置了databaseIdProvider标签。
	 		_databaseId就是代表当前数据库的别名oracle
	  -->
	  
	  <!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
	  <select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">
	  		<!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
	  		<bind name="_lastName" value="'%'+lastName+'%'"/>
	  		<if test="_databaseId=='mysql'">
	  			select * from tbl_employee
	  			<if test="_parameter!=null">
	  				where last_name like #{lastName}
	  			</if>
	  		</if>
	  		<if test="_databaseId=='oracle'">
	  			select * from employees
	  			<if test="_parameter!=null">
	  				where last_name like #{_parameter.lastName}
	  			</if>
	  		</if>
	  </select>

七、bind绑定和sql片段

1、bind

bind元素允许我们通过ognl表达式在上下文中自定义一个变量,最后在动态sql中可以使用这个变量。

<!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
 <select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">
	<!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
	<bind name="_lastName" value="'%'+lastName+'%'"/>
		select * from tbl_employee
		<if test="_parameter!=null">
			where last_name like #{_lastName}
		</if>
  </select>

2、sql/include元素

语法:

<sql id="sql片段id">
各种动态sql
</sql>

抽取可重用的sql片段

<!-- 
  	抽取可重用的sql片段。方便后面引用 
  	1、sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用
  	2、include来引用已经抽取的sql:
  	3、include还可以自定义一些property,sql标签内部就能使用自定义的属性
  			include-property:取值的正确方式${prop},
  			#{不能使用这种方式}
  -->
	<!-- 引用外部定义的sql -->
	<include refid="insertColumn">
	 <property name="testColomn" value="abc"/>
	</include>
	<sql id="insertColumn">
		<if test="_databaseId=='oracle'">
			employee_id,last_name,email
		</if>
		<if test="_databaseId=='mysql'">
			last_name,email,gender,d_id
		</if>
	 </sql>