mybatis动态sql

MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。

虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。

动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

  • if/where
  • choose(when,otherwise)
  • trim(where,set)
  • foreach
if/where
<select id = "find">
	select * from user
	<where>
		<if test = "name != null and name != '' ">
			and name like #{name}	
		</if>
	</where>
</select>
choose when otherwise

当有name的时候就查name当有password的时候就查password
如果都没有就全查

<select id = "find">
	select * from user
	<where>
		<choose>
			<when test="name != null and name != '' ">
				and name like #{name}
			</when>
			<when test = "passworid != null and password != '' ">
				and password like #{password}
			</when>
			<otherwise>
				and featured  = 1
			</otherwise>
		</choose>
	</where>
</select>
trim(自定义where条件) where set
//自定义where条件
<trim prefix = "where" prefixOverrides="AND | OR">	
	...
</trim>

//set的使用
<update id = "update">
	update user 
		<set>
			<if test = "username != null">username = #{username}, </if>
			<if test = "password != null">password = #{password } </if>
		</set>
	where id = #{id}
</update>
foreach
<select id ="find">
	select * from user where id in 
	<foreach item = "id" index = "index" collection="list" open="(  separator="," colse=")">
		#{id}
	</foreach>
</select>

摘自 http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值