MyBatis总结七:动态sql和sql片段

开发中,sql拼接很常见,所以说一下动态sql:

1 if
2 chose,when,otherwise
3 where,set
4 foreach

用法解析(现有一张users表 内有id username age 三个字段):

    <!--查询所有用户,传递参数type,如果值为0,按照年龄升序排序,如果为1则按照年龄降序排序,否则按照ID排序-->
    <!--choose when otherwise的用法  大致相当于case when default-->
    <select id="getUserListByType" resultType="User">
        select * from users
        <choose>
            <when test="type==0">order by age asc</when>
            <when test="type==1">order by age desc</when>
            <otherwise>order by id asc</otherwise>
        </choose>
    </select>

    <!--根据多个id查询用户  if where foreach的用法-->
    <select id="getUserListByIds" resultMap="User">
        select * from users
        <where>
            -- if判断 如果传进去的参数ids不为空
            <if test="ids!=null and ids==''">
                and id in
                -- foreach循环ids 以逗号为分隔符 以ids这个字符串中的'('为开始 ')'为结果
                <foreach collection="ids" item="id" open="(" close=")" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

    <!--修改用户信息,如果某字段为null,则不修改这个字段   set的用法-->
    <select id="updateUser">
        update users
        <set>
            <if test="username!=null and username!=''">
                username = #{username}
            </if>
            <if test="age!=null">
                age = #{age}
            </if>
        </set>
    </select>

我们还可以把重复的sql抽取出来,作为公用的sql片段:

定义sql片段:

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

使用sql片段:

    <!-- 动态sql -->
    <select id="findUserCount" parameterType="com.zy.domain.User" resultType="int">
        select count(*) from users
        -- where 可自动去除条件中的第一个and
        <where>
            <include refid="findUserSql"></include>
        </where>
    </select>

猜你喜欢

转载自www.cnblogs.com/Alex-zqzy/p/9296718.html