Mybatis动态SQL

1.简介

首先什么是动态SQL? 动态SQL有什么作用?

传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach标签,可组合成非常灵活的SQL语句,从而提高开发人员的效率。下面就去感受Mybatis动态SQL的魅力吧。

用官方的话说:

MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。

MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

要学习的mybatis动态 SQL 元素如下:

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

2.where和if

mybatis中使用 where和if 组合

代码示例:

先在映射文件中配置

select id="queryStudentByCondition" resultType="Student">
        select * from student
        <where>
            <if test="id!=null">
                id=#{id}
            </if>
            <if test="name!=null">
                and name=#{name}
            </if>
        </where>
    </select>

再定义接口类方法

  List<Student> queryStudentByCondition(Student condition);
  • 1

测试

  @Test
    public void testQueryDynamicSQL(){
        Student stu=new Student();
        stu.setId(6);
        stu.setName("后土");
        List<Student> studentList=studentDao.queryStudentByCondition(stu);
        log.info("where..if...学生列表:" + studentList);
    }

3.choose和if

mybatis中使用 choose和if 组合

代码示例:

先在映射文件中配置

<select id="queryStudentByChooseWhen" resultType="Student">
        select * from student
        <where>
            <choose>
                <when test="name != null">
                    and name = #{name}
                </when>
                <when test="id != null">
                    and id = #{id}
                </when>
                <otherwise>
                    and id = 5
                </otherwise>
            </choose>
        </where>
    </select>

再定义接口类方法

 List<Student> queryStudentByChooseWhen(Student condittion);

测试

  @Test
    public void testQueryDynamicSQL(){
        Student stu=new Student();
        stu.setId(4);
        stu.setName("共工");
        studentList = studentDao.queryStudentByChooseWhen(stu);
        log.info("choose..when...学生列表:" + studentList);
    }

4.set和trim

<update id="updateStu" parameterType="Student">
        update student
        <!--<set>
            <if test="id!=null">
                id=#{id},
            </if>
            <if test="name!=null">
                 name=#{name}
            </if>
        </set>-->
        <trim prefix="set" suffixOverrides=",">
            <if test="id!=null">
                id=#{id},
            </if>
            <if test="name!=null">
                name=#{name},
            </if>
        </trim>
        where id = #{id}
    </update>

定义接口类方法

 int updateStu(Student condition);
  • 1

测试

  @Test
    public  void testUpdateDynamicSQL(){
        Student student=new Student();
        student.setId(5);
        student.setName("玄冥");
        int rows = studentDao.updateStu(student);
        log.info("更新行数: " + rows);
    }
原文地址:https://www.cnblogs.com/yangsanluo/p/14317434.html