MyBatis的sql元素
与strus2相比而言,myBatis独特于支持可手动编写符合需求的sql语句,并且myBatis结合了Ognl表达式帮助实现sql语句。
mybatis的几种动态sql元素:
- If
- choose
- trim,where.,set
- foreach
1.If:像平常的查询语句,用if来判断是否有值传入,
<select id="getBooks" resultType="map" >
select <include refid="Base_Column_List"/>
from t_book
where 1=1
<if test="bookName != null">
and book_name like CONCAT(CONCAT('%',#{bookName}),'%')
</if>
</select>
2.choose:当书名不为空时,拼接语句,当简介不为空时,拼接下调语句,像这样只是拿几个值来做选择适合用到choose,
<select id="list" resultMap="row" resultType="java.util.List">
select
<include refid="Base_Column_List" />
from t_book
where 1=1
<choose>
<when test="bookName != null">
and book_name like CONCAT(CONCAT('%',#{bookName,jdbcType=VARCHAR}),'%')
</when>
<when test="bookBrief != null">
and book_brief like CONCAT(CONCAT('%',#{bookBrief,jdbcType=VARCHAR}),'%')
</when>
<otherwise ></otherwise>
</choose>
</select>
当这两者都为空时,可最后使用:
<otherwise></otherise>。
3.where 元素知道只有在一个以上的if条件有值的情况下才去插入"WHERE"子句。而且,若最后的内容是"AND"或"OR"开头的,where 元素也知道如何将他们去除。
<select id="findActiveBlogLike" resultType="Blog">
select * from t_book
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
andtitle like #{title}
</if>
<if test="author != null and author.name != null">
andauthor_name like #{author.name}
</if>
</where>
</select>
trim:如果 where 元素没有按正常套路出牌,我们还是可以通过自定义 trim 元素来定制我们想要的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="where" prefixOverrides="and |or ">
...
</trim>
Set:类似的用于动态更新语句的解决方案叫做 set。set 元素可以被用于动态包含需要更新的列,而舍去其他的
<update id="updateByPrimaryKeySelective" parameterType="com.zking.ssm.model.Book" >
update t_book
<set >
<if test="bookName != null" >
book_name = #{bookName,jdbcType=VARCHAR},
</if>
<if test="bookPrice != null" >
book_price = #{bookPrice,jdbcType=REAL},
</if>
<if test="bookBrief != null" >
book_brief = #{bookBrief,jdbcType=VARCHAR},
</if>
</set>
where book_id = #{bookId,jdbcType=INTEGER}
</update>
4:foreach:动态 SQL 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 in条件语句的时候。比如:
<select id="selectPostIn" resultType="domain.blog.Post">
select * form t_book
where book_id in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>