mybatis 详解(五)------动态SQL

  前面几篇博客咱们经过实例讲解了用mybatis对一张表进行的CRUD操做,可是咱们发现写的 SQL 语句都比较简单,若是有比较复杂的业务,咱们须要写复杂的 SQL 语句,每每须要拼接,而拼接 SQL ,稍微不注意,因为引号,空格等缺失可能都会致使错误。java

  那么怎么去解决这个问题呢?这就是本篇所讲的使用 mybatis 动态SQL,经过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成很是灵活的SQL语句,从而在提升 SQL 语句的准确性的同时,也大大提升了开发人员的效率。sql

 

  咱们以 User 表为例来讲明:session

  

一、动态SQL:if 语句

  根据 username 和 sex 来查询数据。若是username为空,那么将只根据sex来查询;反之只根据username来查询mybatis

  首先不使用 动态SQL 来书写app

	<select id="selectUserByUsernameAndSex" 
  			resultType="user" parameterType="com.ys.po.User">
  		<!-- 这里和普通的sql 查询语句差很少,对于只有一个参数,后面的 #{id}表示占位符,里面不必定要写id,
  				写啥均可以,可是不要空着,若是有多个参数则必须写pojo类里面的属性 -->
    	select * from user where username=#{username} and sex=#{sex}
	</select>

  

  上面的查询语句,咱们能够发现,若是 #{username} 为空,那么查询结果也是空,如何解决这个问题呢?使用 if 来判断ide

	<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    	select * from user where 
    		<if test="username != null">
               username=#{username}
           	</if>
    		
    		<if test="username != null">
               and sex=#{sex}
           	</if>
	</select>

  这样写咱们能够看到,若是 sex 等于 null,那么查询语句为 select * from user where username=#{username},可是若是usename 为空呢?那么查询语句为 select * from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句测试

 

二、动态SQL:if+where 语句

	<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    	select * from user 
    	<where>
    		<if test="username != null">
               username=#{username}
           	</if>
    		
    		<if test="username != null">
               and sex=#{sex}
           	</if>
        </where> 
	</select>

  这个“where”标签会知道若是它包含的标签中有返回值的话,它就插入一个‘where’。此外,若是标签返回的内容是以AND 或OR 开头的,则它会剔除掉。this

  

三、动态SQL:if+set 语句

  同理,上面的对于查询 SQL 语句包含 where 关键字,若是在进行更新操做的时候,含有 set 关键词,咱们怎么处理呢?spa

	<!-- 根据 id 更新 user 表的数据 -->
  	<update id="updateUserById" parameterType="com.ys.po.User">
  		update user u
  			<set>
  				<if test="username != null and username != ''">
  					u.username = #{username},
  				</if>
  				<if test="sex != null and sex != ''">
  					u.sex = #{sex}
  				</if>
  			</set>
  		
  		 where id=#{id}
  	</update>

  这样写,若是第一个条件 username 为空,那么 sql 语句为:update user u set u.sex=? where id=?对象

      若是第一个条件不为空,那么 sql 语句为:update user u set u.username = ? ,u.sex = ? where id=?

四、动态SQL:choose(when,otherwise) 语句

  有时候,咱们不想用到全部的查询条件,只想选择其中的一个,查询条件有一个知足便可,使用 choose 标签能够解决此类问题,相似于 Java 的 switch 语句

  <select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User">
    	select * from user 
    	<where>
	    	<choose>
	    		<when test="id !='' and id != null">
	    			id=#{id}
	    		</when>
	    		<when test="username !='' and username != null">
	    			and username=#{username}
	    		</when>
	    		<otherwise>
	    			and sex=#{sex}
	    		</otherwise>
	        </choose> 
    	</where>
	</select>

  也就是说,这里咱们有三个条件,id,username,sex,只能选择一个做为查询条件

    若是 id 不为空,那么查询语句为:select * from user where  id=?

    若是 id 为空,那么看username 是否为空,若是不为空,那么语句为 select * from user where  username=?;

          若是 username 为空,那么查询语句为 select * from user where sex=?

  

五、动态SQL:trim 语句

  trim标记是一个格式化的标记,能够完成set或者是where标记的功能

  ①、用 trim 改写上面第二点的 if+where 语句

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    	select * from user 
    	<!-- <where>
    		<if test="username != null">
               username=#{username}
           	</if>
    		
    		<if test="username != null">
               and sex=#{sex}
           	</if>
        </where>  -->
        <trim prefix="where" prefixOverrides="and | or">
        	<if test="username != null">
               and username=#{username}
           	</if>
    		<if test="sex != null">
               and sex=#{sex}
           	</if>
        </trim>
	</select>

  prefix:前缀      

  prefixoverride:去掉第一个and或者是or

 

  ②、用 trim 改写上面第三点的 if+set 语句

<!-- 根据 id 更新 user 表的数据 -->
  	<update id="updateUserById" parameterType="com.ys.po.User">
  		update user u
  			<!-- <set>
  				<if test="username != null and username != ''">
  					u.username = #{username},
  				</if>
  				<if test="sex != null and sex != ''">
  					u.sex = #{sex}
  				</if>
  			</set> -->
  			<trim prefix="set" suffixOverrides=",">
  				<if test="username != null and username != ''">
  					u.username = #{username},
  				</if>
  				<if test="sex != null and sex != ''">
  					u.sex = #{sex},
  				</if>
  			</trim>
  		
  		 where id=#{id}
  	</update>

  suffix:后缀  

  suffixoverride:去掉最后一个逗号(也能够是其余的标记,就像是上面前缀中的and同样)

 

 

六、动态SQL: SQL 片断

  有时候可能某个 sql 语句咱们用的特别多,为了增长代码的重用性,简化代码,咱们须要将这些代码抽取出来,而后使用时直接调用。

  好比:假如咱们须要常常根据用户名和性别来进行联合查询,那么咱们就把这个代码抽取出来,以下:

	<!-- 定义 sql 片断 -->
	<sql id="selectUserByUserNameAndSexSQL">
		<if test="username != null and username != ''">
  			AND username = #{username}
		</if>
		<if test="sex != null and sex != ''">
			AND sex = #{sex}
		</if>
	</sql>

  引用 sql 片断

	<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    	select * from user 
        <trim prefix="where" prefixOverrides="and | or">
           	<!-- 引用 sql 片断,若是refid 指定的不在本文件中,那么须要在前面加上 namespace -->
           	<include refid="selectUserByUserNameAndSexSQL"></include>
           	<!-- 在这里还能够引用其余的 sql 片断 -->
        </trim>
	</select>

  注意:①、最好基于 单表来定义 sql 片断,提升片断的可重用性

     ②、在 sql 片断中最好不要包括 where 

    

七、动态SQL: foreach 语句

  需求:咱们须要查询 user 表中 id 分别为1,2,3的用户

  sql语句:select * from user where id=1 or id=2 or id=3

       select * from user where id in (1,2,3)

 

①、创建一个 UserVo 类,里面封装一个 List<Integer> ids 的属性

package com.ys.vo;

import java.util.List;

public class UserVo {
	//封装多个用户的id
	private List<Integer> ids;

	public List<Integer> getIds() {
		return ids;
	}

	public void setIds(List<Integer> ids) {
		this.ids = ids;
	}

}  

 

②、咱们用 foreach 来改写 select * from user where id=1 or id=2 or id=3

  	<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
  		select * from user 
  		<where>
  			<!--
  				collection:指定输入对象中的集合属性
  				item:每次遍历生成的对象
  				open:开始遍历时的拼接字符串
  				close:结束时拼接的字符串
  				separator:遍历对象之间须要拼接的字符串
  				select * from user where 1=1 and (id=1 or id=2 or id=3)
  			  -->
  			<foreach collection="ids" item="id" open="and (" close=")" separator="or">
  				id=#{id}
  			</foreach>
  		</where>
  	</select>

  测试:

	//根据id集合查询user表数据
	@Test
	public void testSelectUserByListId(){
		String statement = "com.ys.po.userMapper.selectUserByListId";
		UserVo uv = new UserVo();
		List<Integer> ids = new ArrayList<>();
		ids.add(1);
		ids.add(2);
		ids.add(3);
		uv.setIds(ids);
		List<User> listUser = session.selectList(statement, uv);
		for(User u : listUser){
			System.out.println(u);
		}
		session.close();
	}

  

③、咱们用 foreach 来改写 select * from user where id in (1,2,3)

<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
  		select * from user 
  		<where>
  			<!--
  				collection:指定输入对象中的集合属性
  				item:每次遍历生成的对象
  				open:开始遍历时的拼接字符串
  				close:结束时拼接的字符串
  				separator:遍历对象之间须要拼接的字符串
  				select * from user where 1=1 and id in (1,2,3)
  			  -->
  			<foreach collection="ids" item="id" open="and id in (" close=") " separator=",">
  				#{id}
  			</foreach>
  		</where>
  	</select>

  

 

八、总结

  其实动态 sql 语句的编写每每就是一个拼接的问题,为了保证拼接准确,咱们最好首先要写原生的 sql 语句出来,而后在经过 mybatis 动态sql 对照着改,防止出错。

相关文章
相关标签/搜索