mybatis 之 简单动态sql

1 什么是动态 sql

mybatissql 语句进行灵活操作,通过表达式进行判断,从而对sql进行灵活的封装。

2 if 的用法

需求:从学生表(students)中查询用户信息,对查询条件进行判断,如果不为空,则进行条件拼接。

mapper.xml

<mapper namespace="_4dynamicSql.StudentMapper">


    <select id="findStudents" resultType="_4dynamicSql.Student" 
                parameterType="_4dynamicSql.StudentVo">
        SELECT id,name,sal FROM students

        <!--
                使用where可以自动省掉sql中的第一个and
        -->
        <where>
            <if test="studentCustom!=null">
                <if test=" studentCustom.name != null 
                        and studentCustom.name != ''">
                    AND name = #{studentCustom.name}
                </if>
                <if test="studentCustom.sal != null and   
                        studentCustom.sal != ''">
                    AND sal = #{studentCustom.sal}
                </if>
            </if>
        </where>
    </select>
</mapper>
3 sql片段引用

mybatis.xml

 <!--
        定义 sql 片段
        id:sql片段唯一标示符
    -->
    <sql id="query_student_where" >
        <if test="studentCustom!=null">
            <if test=" studentCustom.name != null and   
                    studentCustom.name != ''">
                and name = #{studentCustom.name}
            </if>
            <if test="studentCustom.sal != null and 
                    studentCustom.sal != ''">
                AND sal = #{studentCustom.sal}
            </if>
        </if>
    </sql>


 <select id="findStudents" resultType="_4dynamicSql.Student" 
            parameterType="_4dynamicSql.StudentVo">
        SELECT id,name,sal FROM students
        <where>
            <include refid="query_student_where"/>
        </where>
    </select>
3 foreach

实现该sql语句的拼接
AND (id=1 OR id=2 OR id=4)

        <!--
            使用 foreach 遍历传入data
            collection:指定输入对象中集合属性
            item:每次遍历的项
            open:开始遍历时拼接的串
            close:结束时遍历拼接的串
            separator:遍历的两个对象之间的串
        -->
        <foreach collection="data" item="item" open=" AND  (" close=")" 
                separator="OR">
            id=#{item}
        </foreach>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容