mybatis的 trim标签tag理解

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE
  <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>
</select>

当上述语句没有条件匹配的时候查询语句就变成了

select * from blog where ;

或者当第二个语句匹配的时候就变成了

select * from bolg where and title like ?;

自然产生了错误 ,那么trim标签就是来解决这样的错误的

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
<trim prefix="where" ,prefixOverrides="and|or">
  <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>
</select>

##上述语句的作用

  • 当语句开头有and或or时自动去掉。
  • 当有条件匹配到时则在最前方加上prifix中的字符, 例如此处的 where。
public class TrimSqlNode implements SqlNode {

  private final SqlNode contents;
  private final String prefix;
  private final String suffix;
  private final List<String> prefixesToOverride;
  private final List<String> suffixesToOverride;
  private final Configuration configuration;

由mybatis的源码可以看到 prefix和suffix是一个String字符串,prefixesToOverride和suffixesToOverride是一个List 列表 对列表中所有字符串进行替换

发布了29 篇原创文章 · 获赞 19 · 访问量 6513

猜你喜欢

转载自blog.csdn.net/wenzhouxiaomayi77/article/details/95625228