mybatis-动态SQL

动态SQL

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

 通常使用动态SQL不可能是独立的一部分,MyBatis当然使用一种强大的动态SQL语言来改进这种情形,这种语言可以被用在任意的SQL映射语句中。

动态SQL元素和使用JSTL或其他类似于XML的文本处理器相似。在MyBatis之前的版本中,有很多的元素需要来了解。MyBatis3大大提升了它们,现在用不到原先一半的元素就可以了。MyBatis采用功能强大的基于OGNL的表达式来消除其他元素。

IF

动态SQL通常要做的事情是有条件的包含where子句的一部分,比如:

<select id="findActiveBlogWithTitleLike" resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’ 
 <if test="title != null">
   AND title like #{title} 
 </if> 
</select>
choose,when,otherwise

 我们不想用到所有的条件语句,而只想从中择其一二。针对这种情况,MyBatis提供了choose元素,它有点像Java中的switch语句。

示例:

 <select id="queryStudentChoose" resultType="student">
    select * from student
    <where>
	   <choose>
	   		<when test="ssex!=null">
	   			and ssex=#{ssex}
	   		</when>
	   		<otherwise>
	   			and ssex=0
	   		</otherwise>
	   </choose>
	 </where>
  </select>
trim,where,set

示例:

<!--
	if 判断条件是否满足  满足就if中的sql  自动拼接到主sql
	where  追加 where 同时去掉第一个and
	
	trim  灵活度更高
		prefix(前缀)   配置的参数会被添加  在sql语句开始的地方(覆盖参数)
		prefixOverrides(前缀覆盖)	sql语句开始出现的参数被覆盖(被覆盖的参数)
		suffix(后缀)	   配置的参数会被添加  在sql语句结尾的地方
		suffixOverrides(后缀覆盖)	sql语句最后出现的参数被覆盖
 -->
 <select id="queryStudentTrim" resultType="student">
    select * from student
    <trim prefix="where" prefixOverrides="and">
    	<if test="sname!=null">
    		and sname like '%${sname}%'
    	</if>
    	<if test="address!=null">
    		and address like '%${address}%'
    	</if>
    </trim>
  </select>
  <!-- 
  	trim 修改后缀
   -->
  <select id="updateStudentTrim" resultType="student">
   update student 
  	 <trim suffix="" suffixOverrides=",">
   	<if test="sname!=null">
   		sname=#{sname},
   	</if>
   	<if test="ssex!=null">
   		ssex=#{ssex},
   	</if>
   	<if test="sage!=null">
   		sage=#{sage},
   	</if>
   	<if test="address!=null">
   		address=#{address},
   	</if>
   </trim>
   where sid=#{sid}
 </select>
  
 <!-- 
 	set标签  动态去掉最后一个条件的,
 		trim实现set
  -->
  <select id="updateStudentSet" resultType="student">
    update student 
   	<set>
    	<if test="sname!=null">
    		sname=#{sname},
    	</if>
    	<if test="ssex!=null">
    		ssex=#{ssex},
    	</if>
    	<if test="sage!=null">
    		sage=#{sage},
    	</if>
    	<if test="address!=null">
    		address=#{address},
    	</if>
    </set>
    where sid=#{sid}
  </select>
 
 
 <select id="queryStudent" resultType="student">
    select * from student
    <where>
    	<if test="sname!=null">
    		and sname like '%${sname}%'
    	</if>
    	<if test="address!=null">
    		and address like '%${address}%'
    	</if>
    </where>
  </select>




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值