MyBatis动态SQL(认真看看, 以后写SQL就爽多了)

作者:微信小助手

发布时间:2019-02-21T08:57:56

作者:阿进的写字台

cnblogs.com/homejim/p/9909657.html



0 一起来学习 mybatis


MyBatis 令人喜欢的一大特性就是动态 SQL。 在使用 JDBC 的过程中, 根据条件进行 SQL 的拼接是很麻烦且很容易出错的。 MyBatis 动态 SQL 的出现, 解决了这个麻烦。

MyBatis通过 OGNL 来进行动态 SQL 的使用的。

目前, 动态 SQL 支持以下几种标签

元素 作用 备注
if 判断语句 单条件分支
choose(when、otherwise) 相当于 Java 中的 if else 多条件分支
trim(where、set) 辅助元素 用于处理 SQL 拼接问题
foreach 循环语句 批量插入, 更新, 查询时经常用到
bind 创建一个变量, 并绑定到上下文中 用于兼容不同的数据库, 防止 SQL 注入等

1 数据准备

为了后面的演示, 创建了一个 Maven 项目 mybatis-dynamic, 创建了对应的数据库和表

DROP TABLE IF EXISTS `student`;CREATE TABLE `student` (  `student_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '编号',  `name` varchar(20) DEFAULT NULL COMMENT '姓名',  `phone` varchar(20) DEFAULT NULL COMMENT '电话',  `email` varchar(50) DEFAULT NULL COMMENT '邮箱',  `sex` tinyint(4) DEFAULT NULL COMMENT '性别',  `locked` tinyint(4) DEFAULT NULL COMMENT '状态(0:正常,1:锁定)',  `gmt_created` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '存入数据库的时间',  `gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改的时间',  `delete` int(11) DEFAULT NULL,
  PRIMARY KEY (`student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='学生表';

对应的项目结构

2 if 标签

if 标签是我们最常使用的。 在查询、删除、更新的时候很可能会使用到。 必须结合 test 属性联合使用。

2.1 在 WHERE 条件中使用 if 标签

这是常见的一种现象, 我们在进行按条件查询的时候, 可能会有多种情况。

2.1.1 查询条件

根据输入的学生信息进行条件检索

  1. 当只输入用户名时, 使用用户名进行模糊检索;

  2. 当只输入性别时, 使用性别进行完全匹配

  3. 当用户名和性别都存在时, 用这两个条件进行查询匹配查询

2.1.2 动态 SQL

接口函数

    /**     * 根据输入的学生信息进行条件检索     * 1. 当只输入用户名时, 使用用户名进行模糊检索;     * 2. 当只输入邮箱时, 使用性别进行完全匹配     * 3. 当用户名和性别都存在时, 用这两个条件进行查询匹配的用     * @param student     * @return     */
        List<Student> selectByStudentSelective(Student student);

对应的动态 SQL

  <select id="selectByStudentSelective" resultMap="BaseResultMap" parameterType="com.homejim.mybatis.entity.Student">    select
    <include refid="Base_Column_List" />    from student    where 1=1
    <if test="name != null and name !=''">      and name like concat('%', #{name}, '%')
    </if>
    <if test="sex != null">      and sex=#{sex}
    </if>
  </select>

在此 SQL 语句中, where 1=1 是多条件拼接时的小技巧, 后面的条件查询就可以都用 and 了。

同时, 我们添加了 if 标签来处理动态 SQL

    <if test="name != null and name !=''">      and name like concat('%', #{name}, '%')
    </if>
    <if test="sex != null">      and sex=#{sex}
    </if>

此 if 标签的 test 属性值是一个符合 OGNL 的表达式, 表达式可以是 true 或 false。 如果表达式返回的是数值, 则0为 false, 非 0 为 true;

2.1.3 测试

      @Test    public void selectByStudent() {
        SqlSession sqlSession = null;
        sqlSession = sqlSessionFactory.openSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

       Student search = new Student();        search.setName("明");

       System.out.println("只有名字时的查询");        List<Student> studentsByName = studentMapper.selectByStudentSelective(search);        for (int i = 0; i < studentsByName.size(); i++) {            System.out.println(ToStringBuilder.reflectionToString(studentsByName.get(i), ToStringStyle.MULTI_LINE_STYLE));        }

       search.setName(null);        search.setSex((byte) 1);        System.out.println("只有性别时的查询");        List<Student> studentsBySex = studentMapper.selectByStudentSelective(search);        for (int i = 0; i < studentsBySex.size(); i++) {            System.out.println(ToStringBuilder.reflectionToString(studentsBySex.get(i), ToStringStyle.MULTI_LINE_STYLE));        }

       System.out.println("姓名和性别同时存在的查询");        search.setName("明");        List<Student> studentsByNameAndSex = studentMapper.selectByStudentSelective(search);        for (int i = 0; i < studentsByNameAndSex.size(); i++) {            System.out.println(ToStringBuilder.reflectionToString(studentsByNameAndSex.get(i), ToStringStyle.MULTI_LINE_STYLE));        }

       sqlSession.commit();        sqlSession.close();    }

只有名字时的查询, 发送的语句和结果

查询的条件只发送了

where 1=1 and name like concat('%', ?, '%') 

只有性别时的查询, 发送的语句和结果

查询的条件只发送了

 where 1=1 and sex=? 

姓名和性别同时存在的查询, 发送的语句和结果

查询条件

where 1=1 and name like concat('%', ?, '%') and sex=? 

2.2 在 UPDATE 更新列中使用 if 标签

有时候我们不希望更新所有的字段, 只更新有变化的字段。

2.2.1 更新条件

只更新有变化的字段, 空值不更新。

2.2.1 动态 SQL

接口方法

    /**     * 更新非空属性     */
    int updateByPrimaryKeySelective(Student record);

对应的 SQL

  <update id="updateByPrimaryKeySelective" parameterType="com.homejim.mybatis.entity.Student">
    update student
    <set>
      <if test="name != null">
        `name` = #{name,jdbcType=VARCHAR},
      </if>
      <if test="phone != null">
        phone = #{phone,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=TINYINT},
      </if>
      <if test="locked != null">
        locked = #{locked,jdbcType=TINYINT},
      </if>
      <if test="gmtCreated != null">
        gmt_created = #{gmtCreated,jdbcType=TIMESTAMP},
      </if>
      <if test="gmtModified != null">
        gmt_modified = #{gmtModified,jdbcType=TIMESTAMP},
      </if>
    </set>    where student_id = #{studentId,jdbcType=I