您的位置:首页 > 数据库

mybatis-动态SQL

2018-02-07 09:19 369 查看
动态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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态sql