动态sql

2016-11-25  本文已影响10人  Stringer

1.where、if

<select id="findUserList" parameterType="cn.ztc.mybatis.po.UserQueryVo" resultType="cn.ztc.mybatis.po.UserCustom">
        select * from user 
        <!-- where可以自动的去掉条件中的第一个and -->
        <where>
            <if test="userCustom.sex!=null">
                <if test="userCustom.sex!=null and userCustom.sex!=''">
                    and user.sex = #{userCustom.sex}
                </if>
                <if test="userCustom.username!=null and userCustom.username!=''">
                    and user.username like '%${userCustom.username}%'
                </if>
            </if>
        </where>
    </select>```

2.sql片段
<!-- 定义sql片段 
    一般是基于单表来定义sql片段,这样的sql片段可重用性高
    在sqk片段中不要包含where
-->
<sql id="query_user_where">
    <if test="userCustom.sex!=null!=null">
        <if test="userCustom.sex!=null and userCustom.sex!=''">
            and user.sex = #{userCustom.sex}
        </if>
        <if test="userCustom.username!=null and userCustom.username!=''">
            and user.username like '%${userCustom.username}%'
        </if>
    </if>
</sql>

<select id="findUserList" parameterType="cn.ztc.mybatis.po.UserQueryVo" resultType="cn.ztc.mybatis.po.UserCustom">
    select * from user 
    <!-- 可以自动的去掉条件中的第一个and -->
    <where>
    <!-- 引用sql片段 -->
        <include refid="query_user_where"></include>
    </where>
</select>```

3.foreach

<sql id="query_user_where">
        <if test="userCustom.sex!=null!=null">
            <if test="userCustom.sex!=null and userCustom.sex!=''">
                and user.sex = #{userCustom.sex}
            </if>
            <if test="userCustom.username!=null and userCustom.username!=''">
                and user.username like '%${userCustom.username}%'
            </if>
            <if test="ids!=null">
                <!--    使用foreach遍历ids
                    collection:指定输入对象中的集合属性名
                    item:遍历生成的对象名
                    open:开始遍历时的拼接串
                    close:结束遍历时的拼接串
                    separator:遍历的两个对象中间的拼接串
                 -->
                <foreach collection="ids" item="user_id" open="and(" close=")" separator="or">
                    <!-- 每次遍历需要拼接的串 
                         and( id=? or id=? or id=? )
                    -->
                    id=#{user_id}
                </foreach>
            </if>
        </if>
    </sql>```
上一篇 下一篇

猜你喜欢

热点阅读