【MyBatis学习09】SQL片段

来源:互联网 发布:notepad python插件 编辑:程序博客网 时间:2024/06/05 03:59

本文博客地址:http://blog.csdn.net/soonfly/article/details/63688057 (转载请注明出处)

在写SQL语句时,有很多是可以重用的,比如前台显示会员,必须是审核通过、没有软删除、没有被锁定。
那么这条件应该是公用:isdel=0 and islock=0 and isvalidate=1
因为在所有外部场景中查询用户的语句中都要用到,如查询单个,搜索用户列表,查询商品购买用户等等。

基于重用的思想,mybatis提供了sql片段。

一、创建

<sql id="member_mustWhere">    and isdel=0 and islock=0 and isvalidate=1</sql>

二、使用

<select id="findByName" parameterType="String" resultType="twm.mybatisdemo.pojo.User">    <bind name="likestr" value="'%'+ searchkey +'%'"></bind>        select * from user        <where>              <if test="searchkey !='' and searchkey !=null">                username like #{likestr}            </if>            <!-- sql片段引入 -->              <include refid="member_mustWhere"></include>      </where></select>

sql片段只能在同一个mapper上下文中使用,同一上下文中的不同sql片段的id必须唯一。
sql片段可以嵌套引用:

<sql id="member_mustWhere">    and isdel=0 and islock=0     <include refid="member_mustWhere_validate"></include></sql>  <sql id="member_mustWhere_validate">and isvalidate=1</sql><select id="findByName" parameterType="String" resultType="twm.mybatisdemo.pojo.User">    <bind name="likestr" value="'%'+ searchkey +'%'"></bind>    select * from user    <where>        <if test="searchkey !='' and searchkey !=null">            username like #{likestr}        </if>        <!-- sql片段引入 -->        <include refid="member_mustWhere"></include>    </where></select>

本文博客地址:http://blog.csdn.net/soonfly/article/details/63688057 (转载请注明出处)

0 0
原创粉丝点击