`
234390216
  • 浏览: 10193521 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
博客专栏
A5ee55b9-a463-3d09-9c78-0c0cf33198cd
Oracle基础
浏览量:460809
Ad26f909-6440-35a9-b4e9-9aea825bd38e
springMVC介绍
浏览量:1771817
Ce363057-ae4d-3ee1-bb46-e7b51a722a4b
Mybatis简介
浏览量:1395439
Bdeb91ad-cf8a-3fe9-942a-3710073b4000
Spring整合JMS
浏览量:393893
5cbbde67-7cd5-313c-95c2-4185389601e7
Ehcache简介
浏览量:678226
Cc1c0708-ccc2-3d20-ba47-d40e04440682
Cas简介
浏览量:529302
51592fc3-854c-34f4-9eff-cb82d993ab3a
Spring Securi...
浏览量:1178743
23e1c30e-ef8c-3702-aa3c-e83277ffca91
Spring基础知识
浏览量:461913
4af1c81c-eb9d-365f-b759-07685a32156e
Spring Aop介绍
浏览量:150147
2f926891-9e7a-3ce2-a074-3acb2aaf2584
JAXB简介
浏览量:66858
社区版块
存档分类
最新评论

MyBatis的动态SQL详解

阅读更多

基础部分可以查看我的另一篇博客:http://elim.iteye.com/blog/1333271

 

MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。

MyBatis中用于实现动态SQL的元素主要有:

 

  • if
  • choose(when,otherwise)
  • trim
  • where
  • set
  • foreach
if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。先来看如下一个例子:
	<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
		select * from t_blog where 1 = 1
		<if test="title != null">
			and title = #{title}
		</if>
		<if test="content != null">
			and content = #{content}
		</if>
		<if test="owner != null">
			and owner = #{owner}
		</if>
	</select>
这条语句的意思非常简单,如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了。
 
choose元素的作用就相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常都是与when和otherwise搭配的。看如下一个例子:
	<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
		select * from t_blog where 1 = 1 
		<choose>
			<when test="title != null">
				and title = #{title}
			</when>
			<when test="content != null">
				and content = #{content}
			</when>
			<otherwise>
				and owner = "owner1"
			</otherwise>
		</choose>
	</select>
when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时候,就会跳出choose,即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的内容。所以上述语句的意思非常简单, 当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。
 
where语句的作用主要是简化SQL语句中where中的条件判断的,先看一个例子,再解释一下where的好处。
	<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
		select * from t_blog 
		<where>
			<if test="title != null">
				title = #{title}
			</if>
			<if test="content != null">
				and content = #{content}
			</if>
			<if test="owner != null">
				and owner = #{owner}
			</if>
		</where>
	</select>
 where元素的作用是会在写入where元素的地方输出一个where,另外一个好处是你不需要考虑where元素里面的条件输出是什么样子的,MyBatis会智能的帮你处理,如果所有的条件都不满足那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略;此外,在where元素中你不需要考虑空格的问题,MyBatis会智能的帮你加上。像上述例子中,如果title=null, 而content != null,那么输出的整个语句会是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因为MyBatis会智能的把首个and 或 or 给忽略。
 
trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能,示例代码如下:
	<select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
		select * from t_blog 
		<trim prefix="where" prefixOverrides="and |or">
			<if test="title != null">
				title = #{title}
			</if>
			<if test="content != null">
				and content = #{content}
			</if>
			<if test="owner != null">
				or owner = #{owner}
			</if>
		</trim>
	</select>
 
set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段。下面是一段示例代码:
	<update id="dynamicSetTest" parameterType="Blog">
		update t_blog
		<set>
			<if test="title != null">
				title = #{title},
			</if>
			<if test="content != null">
				content = #{content},
			</if>
			<if test="owner != null">
				owner = #{owner}
			</if>
		</set>
		where id = #{id}
	</update>
 上述示例代码中,如果set中一个条件都不满足,即set中包含的内容为空的时候就会报错。
 
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:
  1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
  2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key
下面分别来看看上述三种情况的示例代码:
1.单参数List的类型:
	<select id="dynamicForeachTest" resultType="Blog">
		select * from t_blog where id in
		<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
			#{item}
		</foreach>
	</select>
 上述collection的值为list,对应的Mapper是这样的
public List<Blog> dynamicForeachTest(List<Integer> ids);
 测试代码:
	@Test
	public void dynamicForeachTest() {
		SqlSession session = Util.getSqlSessionFactory().openSession();
		BlogMapper blogMapper = session.getMapper(BlogMapper.class);
		List<Integer> ids = new ArrayList<Integer>();
		ids.add(1);
		ids.add(3);
		ids.add(6);
		List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
		for (Blog blog : blogs)
			System.out.println(blog);
		session.close();
	}
 
2.单参数array数组的类型:
	<select id="dynamicForeach2Test" resultType="Blog">
		select * from t_blog where id in
		<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
			#{item}
		</foreach>
	</select>
 上述collection为array,对应的Mapper代码:
public List<Blog> dynamicForeach2Test(int[] ids);
 对应的测试代码:
	@Test
	public void dynamicForeach2Test() {
		SqlSession session = Util.getSqlSessionFactory().openSession();
		BlogMapper blogMapper = session.getMapper(BlogMapper.class);
		int[] ids = new int[] {1,3,6,9};
		List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
		for (Blog blog : blogs)
			System.out.println(blog);
		session.close();
	}
 
3.自己把参数封装成Map的类型
	<select id="dynamicForeach3Test" resultType="Blog">
		select * from t_blog where title like "%"#{title}"%" and id in
		<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
			#{item}
		</foreach>
	</select>
上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
public List<Blog> dynamicForeach3Test(Map<String, Object> params);
  对应测试代码:
	@Test
	public void dynamicForeach3Test() {
		SqlSession session = Util.getSqlSessionFactory().openSession();
		BlogMapper blogMapper = session.getMapper(BlogMapper.class);
		final List<Integer> ids = new ArrayList<Integer>();
		ids.add(1);
		ids.add(2);
		ids.add(3);
		ids.add(6);
		ids.add(7);
		ids.add(9);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("ids", ids);
		params.put("title", "中国");
		List<Blog> blogs = blogMapper.dynamicForeach3Test(params);
		for (Blog blog : blogs)
			System.out.println(blog);
		session.close();
	}
 
 
基础部分可以查看我的另一篇博客:http://haohaoxuexi.iteye.com/blog/1333271

基于3.3.1版本验证的新特性

 本文是基于Mybatis 3.0.6版本所写,笔者最近在查看新版Mybatis(3.3.1)时发现其对动态SQL的支持较以前的3.0.6版本的区别不大,基本一致,但笔者还是发现有以下新特性:
1、foreach标签遍历的集合元素类型是Map.Entry类型时,index属性指定的变量代表对应的Map.Entry的key,item属性指定的变量代表对应的Map.Entry的value。此时如果对应的集合是Map.entrySet,则对应的collection属性用collection。foreach在进行遍历的时候如果传入的参数是List类型,则其collection属性的值可以是list或collection,但如果传入的参数是Set类型,则collection属性的值只能用collection。
	<select id="dynamicForeachTest" resultType="Blog">
		select * from t_blog where id in
		<!-- 遍历的对象是Map.Entry时,index代表对应的key,item代表对应的value -->
		<foreach collection="collection" index="key" item="value" open="(" separator="," close=")">
			#{key}, #{value}
		</foreach>
	</select>
 其对应的接口方法大概是如下这样:
    public List<Blog> dynamicForeachTest(Set<Map.Entry<Integer, Integer>> ids);
 
2、bind标签,动态SQL中已经包含了这样一个新的标签,它的功能是在当前OGNL上下文中创建一个变量并绑定一个值。有了它以后我们以前的模糊查询就可以改成这个样子:
    <select id="fuzzyQuery" resultType="Blog" parameterType="java.lang.String">  
    	<!-- bind标签用于创建新的变量 -->
		<bind name="titleLike" value="'%'+_parameter+'%'"/>
        select * from t_blog where title like #{titleLike}  
    </select>
  
 
 
 
 
 
 
 
 
 
 
43
5
分享到:
评论
13 楼 吾乃隔壁老王 2016-11-07  
3Q,问个问题啊,where里的if里,能不能不加and?
12 楼 yuang 2015-12-29  
" target="_blank">" />" target="_blank">" wmode="" quality="high" menu="false" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="200" height="200">[b][/b]
11 楼 happymzw 2014-12-04  
Syhenian 写道
<update id="dynamicSetTest" parameterType="Blog">  
    update t_blog  
    <set>  
        <if test="title != null">  
            title = #{title},  
        </if>  
        <if test="content != null">  
            content = #{content},  
        </if>  
        <if test="owner != null">  
            owner = #{owner}  
        </if>  
    </set>  
    where id = #{id}  
</update>  


这段可以这样写吗   如果ownner等于null   那语句就是

update t_blog title= 'title', content='content',  where id='id'

多了个红色的逗号不会报错?


楼主说了,set会自动处理掉后面的那个逗号的
10 楼 简单就是美了 2014-11-20  
    
9 楼 shiping8000 2014-11-06  
写的不错,给赞 
8 楼 Syhenian 2014-08-29  
<update id="dynamicSetTest" parameterType="Blog">  
    update t_blog  
    <set>  
        <if test="title != null">  
            title = #{title},  
        </if>  
        <if test="content != null">  
            content = #{content},  
        </if>  
        <if test="owner != null">  
            owner = #{owner}  
        </if>  
    </set>  
    where id = #{id}  
</update>  


这段可以这样写吗   如果ownner等于null   那语句就是

update t_blog title= 'title', content='content',  where id='id'

多了个红色的逗号不会报错?
7 楼 slc2006119 2014-06-27  
简单,易懂,确实写的不错,赞一个!
6 楼 dmewy 2014-06-12  
不错 适合开发初期看
5 楼 宋建勇 2014-05-28  
今天整合MyBatis,帮了大忙了啊!不错啊!
4 楼 18289753290 2014-05-23  
不错 
3 楼 lcg19880128 2014-03-14  
  
2 楼 coffeeBoy2012 2014-02-07  
很详细
1 楼 huxiulei 2013-11-22  
嗯  写的不错... 简明易懂

相关推荐

    mybatis动态sql

    mybatis动态sql详解,网络查询,自己实践整理,希望对大家有帮助

    mybatis的动态sql详解(精)

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下

    MyBatis的动态SQL详解[借鉴].pdf

    MyBatis的动态SQL详解[借鉴].pdf

    MyBatis 执行动态 SQL语句详解

    大家对mybatis执行任意sql语句都了解,那么MyBatis执行动态SQL语句呢?下面脚本之家小编给大家解答下mybatis执行动态sql语句的方法,非常不错,感兴趣的朋友参考下吧

    MyBatis 动态SQL和缓存机制实例详解

    主要介绍了MyBatis 动态SQL和缓存机制实例详解,非常不错,具有参考借鉴价值,需要的朋友可以参考下

    MyBatis笔记详解以及动态SQL

    MyBatis笔记详解以及动态SQL。

    MyBatis动态SQL标签用法实例详解

    本文通过实例代码给大家介绍了MyBatis动态SQL标签用法,非常不错,具有参考借鉴价值,需要的朋友参考下吧

    mybatis 实现 SQL 查询拦截修改详解

    主要介绍了mybatis 实现 SQL 查询拦截修改详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    详解Mybatis动态sql

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。本文给大家介绍Mybatis动态sql小结,感兴趣的朋友参考下

    详解MyBatis直接执行SQL查询及数据批量插入

    主要介绍了MyBatis直接执行SQL查询及数据批量插入的相关知识,需要的朋友一起学习吧

    MyBatis动态Sql之if标签的用法详解

    主要介绍了MyBatis动态Sql之if标签的用法,本文给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下

    Mybatis的详解以及使用

    这是Mybatis的详解以及使用,里面包括我写的一个小例子以及数据库表结构和数据的sql语句。详细介绍了mybatis的使用方法。

    mybatis和mybatis plus比较详解

    MyBatis提供了定制化SQL、存储过程以及高级映射的支持,它要求开发者手动编写SQL语句,并使用注解或XML文件进行配置。相比之下,MyBatis Plus则提供了更为丰富的功能,如自动注入基本CRUD操作、强大的条件构造器、...

    Mybatis动态SQL之if、choose、where、set、trim、foreach标记实例详解

    动态SQL就是动态的生成SQL。接下来通过本文给大家介绍Mybatis动态SQL之if、choose、where、set、trim、foreach标记实例详解的相关知识,感兴趣的朋友一起看看吧

    mybatis防止SQL注入的方法实例详解

    SQL注入是一种很简单的攻击手段,但直到今天仍然十分常见。那么mybatis是如何防止SQL注入的呢?下面脚本之家小编给大家带来了实例代码,需要的朋友参考下吧

    mybatis逆向工程详解源码

    MyBatis的一个主要的特点就是需要程序员自己编写sql,那么如果表太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单表自动生成mybatis执行所需要的代码(包括mapper.xml、mapper.java、po..)...

    Mybatis-03 SQL映射文件

    详解MyBatis框架中SQL映射文件的具体配置,包括实现增删改查操作、根据主键生成方式获取主键值、针对单个参数、多个参数和命名参数的处理与参数值获取以及select标签中resultMap的详解

    springboot整合mybatis将sql打印到日志的实例详解

    主要介绍了springboot整合mybatis将sql打印到日志的实例详解,需要的朋友可以参考下

    mybatis入门到精通详解

    视频包含:mybatis入门;...MyBatis配置文件编写,MyBatis动态SQL,MyBatis缓存机制,MyBatis-Spring整合,MyBatis逆向工程,MyBatis高级映射等等,适合入门级java学员(由于文件过大,此处放网盘下载链接)

Global site tag (gtag.js) - Google Analytics