mybatis14 动态sql

动态sql(重点)
mybatis重点是对sql的灵活解析和处理。

1.1需求
将自定义查询条件查询用户列表和查询用户列表总记录数改为动态sql

1.2if和where
<!-- 自定义查询条件查询用户的信息
    parameterType:指定包装类型
    %${userCustom.username}%:userCustom是userQueryVo中的属性,通过OGNL获取属性的值
     -->
    <select id="findUserList" parameterType="userQueryVo" resultType="user">
        select id,username,birthday from user 
    <where>
        <!-- where标签相当 于where关键字,可以自动去除第一个and -->
        <if test="userCustom!=null">
                <if test="userCustom.username!=null and userCustom.username!=''">
                    and username like '%${userCustom.username}%'
                </if>
                <if test="userCustom.sex!=null and userCustom.sex!=''">
                    and sex = #{userCustom.sex}
                </if>clude refid="其它的sql片段"></include> -->
     </if>
        </where>
    </select>
1.1sql片段
通过sql片段可以将通用的sql语句抽取出来,单独定义,在其它的statement中可以引用sql片段。
通用的sql语句,常用:where条件、查询列

1.1.1sql片段的定义

 

1.1.1 引用sql片段

foreach

在statement通过foreach遍历parameterType中的集合类型。

需求:
根据多个用户id查询用户信息。


1.1.1在userQueryVo中定义list<Integer> ids

在userQueryvo中定义list<Integer> ids存储多个id

1.1.1修改where语句

使用foreach遍历list:
<foreach collection="ids" open=" AND id IN ( " close=")" item="id" separator=",">
                     #{id}    <!-- 16,循环 -->
                 </foreach>
    <!-- 
    如果拼接 SELECT id ,username ,birthday  FROM USER WHERE username LIKE '%小明%' AND (开始                id = 16 OR id = 22 OR id = 25循环             )结束 
     <foreach collection="ids" open=" AND ( " close=")" item="id" separator="OR">
                     id = #{id}   <!--  id = 16 ,循环 -->
</foreach>

1.1.1 测试代码

原文地址:https://www.cnblogs.com/yaowen/p/4869747.html