1 動態(tài)SQL
傳統(tǒng)的使用JDBC的方法,相信大家在組合復(fù)雜的的SQL語句的時候雾狈,需要去拼接廓潜,稍不注意哪怕少了個空格,都會導(dǎo)致錯誤善榛。Mybatis的動態(tài)SQL功能正是為了解決這種問題辩蛋, 其通過 if, choose, when, otherwise, trim, where, set, foreach標簽,可組合成非常靈活的SQL語句移盆,從而提高開發(fā)人員的效率
- if sqlNode
<select id="findUserById" resultType="user">
select * from user where
deleteFlag = 0
<if test="id != null">
AND id=#{id}
</if>
</select>
- where SqlNode
<select id="findUserById" resultType="user">
select * from user
<where>
<if test="id != null">
id=#{id}
</if>
</where>
</select>
- trim sqlNode
<select id="findUserById" resultType="user">
select * from user
<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="id != null">
AND id=#{id}
</if>
</trim>
</select>
- set SqlNode
<update id="updateUser" parameterType="com.dy.entity.User">
update user
<trim prefix="SET" suffixOverrides=",">
<if test="name != null">name = #{name},</if>
<if test="password != null">password = #{password},</if>
<if test="age != null">age = #{age},</if>
</trim>
<where>
<if test="id != null">
id = #{id}
</if>
and deleteFlag = 0;
</where>
</update>
- foreach sqlNode
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
- choose sqlNode
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>