动态SQL之标签
Posted 菜包包
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态SQL之标签相关的知识,希望对你有一定的参考价值。
本节主要讲了动态SQL的几个标签:where set trim
where: 检出where语句的最前面是否含有AND和一个空格 或者 or和一个空格 ,如果有的话删除
set: 检出set的最后是否有逗号 ,如果有,则清空
trim:可用来替换where和set
foreach:遍历集合(array,list,key)
CDATA:不支持标签,用于有<等需要<时
where 和 if 条件查询
<select id="whereMore01" resultType="com.shxt.model.User">
SELECT
*
FROM user
<where>
<if test="user_name!=null and user_name.length() >0">
AND user_name like CONCAT(#{user_name},‘%‘)
</if>
<!-- && 不推荐记忆 << -->
<if test="account!=null and account.length() > 0">
AND account = #{account}
</if>
</where>
</select>
set 和 if 更新对象信息
<update id="update01" parameterType="com.shxt.model.User" >
UPDATE user
<set>
<if test="account!=null">
account =#{account},
</if>
<if test="password!=null">
password = #{password},
</if>
<if test="user_name!=null">
user_name =#{user_name},
</if>
</set>
WHERE
id = #{id}
</update>
trim替换
替换条件查询where
<select id="whereMore02" resultType="com.shxt.model.User">
SELECT
*
FROM user
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="user_name!=null and user_name.length() >0">
AND user_name like CONCAT(#{user_name},‘%‘)
</if>
<!-- && 不推荐记忆 << -->
<if test="account!=null and account.length() > 0">
AND account = #{account}
</if>
</trim>
</select>
替换更新操作set
<update id="update02" parameterType="com.shxt.model.User" >
UPDATE user
<trim prefix="set" suffixOverrides=",">
<if test="account!=null">
account =#{account},
</if>
<if test="password!=null">
password = #{password},
</if>
<if test="user_name!=null">
user_name =#{user_name},
</if>
</trim>
WHERE
id = #{id}
</update>
foreach遍历in(2,3,4,5)
<select id="collectionTest" resultType="User">
select * from user where id in
<foreach collection="list|array|key" index = "index" item="us" open="(" close=")" separator=",">
#{us}
</foreach>
</select>
CDATA:查询小于id的集合
<![CDATA[
select * from user where id < #{id}
]]>
以上是关于动态SQL之标签的主要内容,如果未能解决你的问题,请参考以下文章
MyBatis 之四(动态SQL之 iftrimwheresetforeach 标签)
Java--MyBatis动态SQL;<if>,<where>,<foreach>标签
Mybatis -- 动态Sql概述动态Sql之<if>(包含<where>)动态Sql之<foreach>sql片段抽取