mybatis的sql片段使用

在开发中,SQL的拼接很常见,有很对拼接的sql具有重复性高的特点,这时最好把重复的sql抽取出来,作为公用的sql片段。

定义sql片段:

<!-- sql片段 
        建议:对单表进行sql片段的抽取,方便重用
            抽取时不包含where
     -->
     <sql id="findUserSql">
        <if test="userCustomer!=null">
                <if test="userCustomer.sex!=null and userCustomer.sex!=''">
                    and user.sex=#{userCustomer.sex}
                </if>
                <if test="userCustomer.address!=null and userCustomer.address!=''">
                    and user.address like '$%{userCustomer.address}%'
                </if>
        </if>
     </sql>
  •  

引用sql片段:

<!-- 动态sql -->
    <select id="fingUserList" parameterType="com.hl.myabtis.first.beas.UserQueryVo" resultType="com.hl.myabtis.first.beas.UserCustomer">
        select * from user
        <!-- where可以自动去掉条件中的第一个and -->
        <where>
            <include refid="findUserSql"></include>
        </where>

    </select>
    <select id="findUserCount" parameterType="com.hl.myabtis.first.beas.UserQueryVo" resultType="int">
        select count(*) from user 
        <where>
            <include refid="findUserSql"></include>
        </where>
    </select>

猜你喜欢

转载自blog.csdn.net/qq_33238935/article/details/82458325