SQL片段的作用:将重复的SQL语句抽取出来,放到<sql>标签中,可以进行复用。
1.抽取重复的SQL语句
<sql id="where-title-author">
<if test="title!=null">
title like concat('%',#{title},'%')
</if>
<if test="author!=null">
and author = #{author}
</if>
</sql>
2.在SQL语句中引入SQL片段
<select id="queryBlogIf" resultType="blog" parameterType="map">
select * from mybatis.blog
<where>
<include refid="where-title-author"></include>
</where>
</select>
注意:最好不要太复杂的语句
不要将<where>和<set>标签放到SQL片段中。
本文介绍了如何在MyBatis中通过SQL片段来抽取和复用重复的查询条件,提高代码的可读性和维护性。示例展示了如何创建包含条件判断的SQL片段,并在实际查询中引用这些片段,简化复杂SQL的编写,同时避免在片段中使用<where>和<set>标签,以保持简洁性。
382

被折叠的 条评论
为什么被折叠?



