J2EE进阶学习——Mybatis(五):动态sql

1.什么是动态sql

mybatis核心对sql语句进行灵活操作,通过表达式进行推断,对sql进行灵活拼接、组装。 将

2.需求

用户信息综合查询列表和用户信息查询列表总数这两个statement的定义使用动态sql。

对查询条件进行判断,如果输入参数不为空才进行查询条件的拼接

<select id="findUserList" parameterType="com.TiHom.mybatis.po.UserQueryVo"
            resultType="com.TiHom.mybatis.po.UserCustom">
        select * from user
        <!--自动去掉条件中的第一个and-->
        <where>
            <if test="userCustom!=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 '%${value}%'
                </if>
            </if>
        </where>
    </select>

这里使用动态sql,如果不设置某个值,条件不会拼接在sql中

3.sql片段

3.1需求

将上边实现的动态代理块抽取出来,组成一个sql片段。其它的statement中就可以引用sql片段。方便程序员开发

3.2定义sql片段
    <!-- 定义sql片段
    id:sql片段的唯一标识

    一般来说,是基于单表来定义sql片段,这样的话这个sql片段的可重用性才高
    在sql片段中不要包含where
    -->
    <sql id="query_user_where">
            <if test="userCustom!=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 '%${value}%'
                </if>
            </if>
    </sql>
3.3引用sql片段
    <select id="findUserList" parameterType="com.TiHom.mybatis.po.UserQueryVo"
            resultType="com.TiHom.mybatis.po.UserCustom">
        select * from user
        <!--自动去掉条件中的第一个and-->
        <where>
            <!-- 引用sql片段的id,如果refid指定的id不在本mapper文件中,加上namespace -->
            <include refid="query_user_where"></include>
            <!-- 在这里还需要引用其他的sql片段 -->
        </where>
    </select>

4.foreach

向sql传递数组或List,mybatis使用foreach解析
在用户查询列表和查询总数的statement中增加多个id输入查询。
sql语句实现如下:
1.

2.

猜你喜欢

转载自blog.csdn.net/tryandfight/article/details/79587884