mybatis 的trim标签的使用,属性prefix,suffix,prefixOverrides,suffixOverrides
作用:解决sql拼接问题。第一种:where ... and..第二种:入参对象,有些字段为null或者空,在写sql的增删改查时,就不应该加入了,就会面临拼接时多 逗号‘,’1、trime标签相当于where标签的作用:<trim prefix="WHERE" prefixOverrides="AND"><if test="stat...
·

作用:解决sql拼接问题。
第一种:where ... and..
第二种:入参对象,有些字段为null或者空,在写sql的增删改查时,就不应该加入了,就会面临拼接时多 逗号‘,’
1、trime标签相当于where标签的作用:
<trim prefix="WHERE" prefixOverrides="AND">
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</trim>
单句解释:在<if> <if/>等标签最终完成拼接的sql语句进行操作,where + 拼接sql +如果AND开头,去除AND。
<trim prefix="WHERE" prefixOverrides="AND">
prefix="WHERE"不参与sql拼接,意思就是直接在sql前面+where关键字
<trim>标签也就是作用范围在这段:
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
某部分条件满足,sql正常,sql拼接成
state = #{state} AND title like #{title}
特殊情况:如果最终拼接成这样,就会去除AND
AND title like ‘someTitle’
配置了prefixOverrides="AND变成
title like ‘someTitle’
where标签介绍:
where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。
而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
2、去除多余的逗号等
<trim prefix="set" suffixOverrides=",">
比如要插入user对象值,如果名字为空,或者年龄为空,则不更新这些字段
如果写成原来的:
insert into (username,password,age,address,phone)
values
(#{username},#{password},#{age},#{address},#{phone});
或者<if>标签配合用,都会有很大的问题
直接上例子吧
<!--对应的接口 int updateStreamBoxes(@Param("list") List<SBox> list);-->
<update id="updateStreamBoxes" parameterType="list">
update stream_box
<trim prefix="set" suffixOverrides=",">
<trim prefix="use_state =case" suffix="end,">
<foreach collection="list" item="i" index="index">
when stream_box_id=#{i.streamBoxId} then #{i.useState}
</foreach>
</trim>
<trim prefix=" set_id =case" suffix="end,">
<foreach collection="list" item="i" index="index">
when stream_box_id=#{i.streamBoxId} then #{i.setId}
</foreach>
</trim>
<trim prefix=" pre_set_id =case" suffix="end,">
<foreach collection="list" item="i" index="index">
when stream_box_id=#{i.streamBoxId} then #{i.preSetId}
</foreach>
</trim>
<trim prefix=" pre_use_capability =case" suffix="end,">
<foreach collection="list" item="i" index="index">
when stream_box_id=#{i.streamBoxId} then #{i.preUseCapability}
</foreach>
</trim>
<trim prefix=" last_set_id =case" suffix="end,">
<foreach collection="list" item="i" index="index">
when stream_box_id=#{i.streamBoxId} then #{i.lastSetId}
</foreach>
</trim>
<trim prefix=" last_use_capability =case" suffix="end,">
<foreach collection="list" item="i" index="index">
when stream_box_id=#{i.streamBoxId} then #{i.lastUseCapability}
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="i" index="index" >
stream_box_id=#{i.streamBoxId}
</foreach>
</update>
参考:https://blog.csdn.net/wt_better/article/details/80992014
更多推荐



所有评论(0)