[Java]Mybatis

[Java]Mybatis

学习使用工具

黑马2023新版Java视频教程 https://www.bilibili.com/video/BV1Fv4y1q7ZH?p=8&vd_source=03da0cdb826d78c565cd22a83928f4c2

http://c.biancheng.net/mybatis/

零、Lombok

Lombok是一个实用的Java类库,可以通过简单的注解来简化和消除一些必须有但显得很臃肿的Java代码。通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,并可以自动化生成日志变量,简化java开发、提高效率。

注解 作用
@Getter/@Setter 为所有的属性提供get/set方法
@ToString 会给类自动生成易阅读的 toString 方法
@EqualsAndHashCode 根据类所拥有的非静态字段自动重写 equals 方法和 hashCode 方法
@Data 提供了更综合的生成代码功能(@Getter + @Setter + @ToString + @EqualsAndHashCode)
@NoArgsConstructor 为实体类生成无参的构造器方法
@AllArgsConstructor 为实体类生成除了static修饰的字段之外带有各参数的构造器方法。

第1步:在pom.xml文件中引入依赖

<!-- 在springboot的父工程中,已经集成了lombok并指定了版本号,故当前引入依赖时不需要指定version -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

第2步:在实体类上添加注解

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String name;
    private Short age;
    private Short gender;
    private String phone;
}

在实体类上添加了@Data注解,那么这个类在编译时期,就会生成getter/setter、equals、hashcode、toString等方法。

说明:@Data注解中不包含全参构造方法,通常在实体类上,还会添加上:全参构造、无参构造

import lombok.Data;

@Data //getter方法、setter方法、toString方法、hashCode方法、equals方法
@NoArgsConstructor //无参构造
@AllArgsConstructor//全参构造
public class User {
    private Integer id;
    private String name;
    private Short age;
    private Short gender;
    private String phone;
}

Lombok的注意事项:

  • Lombok会在编译时,会自动生成对应的java代码
  • 在使用lombok时,还需要安装一个lombok的插件(新版本的IDEA中自带)

一、Mybatis基础操作

  • 环境准备

    1. 准备数据库表

      -- 部门管理
      create table dept
      (
          id          int unsigned primary key auto_increment comment '主键ID',
          name        varchar(10) not null unique comment '部门名称',
          create_time datetime    not null comment '创建时间',
          update_time datetime    not null comment '修改时间'
      ) comment '部门表';
      -- 部门表测试数据
      insert into dept (id, name, create_time, update_time)
      values (1, '学工部', now(), now()),
             (2, '教研部', now(), now()),
             (3, '咨询部', now(), now()),
             (4, '就业部', now(), now()),
             (5, '人事部', now(), now());
      -- 员工管理
      create table emp
      (
          id          int unsigned primary key auto_increment comment 'ID',
          username    varchar(20)      not null unique comment '用户名',
          password    varchar(32) default '123456' comment '密码',
          name        varchar(10)      not null comment '姓名',
          gender      tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
          image       varchar(300) comment '图像',
          job         tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
          entrydate   date comment '入职时间',
          dept_id     int unsigned comment '部门ID',
          create_time datetime         not null comment '创建时间',
          update_time datetime         not null comment '修改时间'
      ) comment '员工表';
      -- 员工表测试数据
      INSERT INTO emp (id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time)
      VALUES 
      (1, 'jinyong', '123456', '金庸', 1, '1.jpg', 4, '2000-01-01', 2, now(), now()),
      (2, 'zhangwuji', '123456', '张无忌', 1, '2.jpg', 2, '2015-01-01', 2, now(), now()),
      (3, 'yangxiao', '123456', '杨逍', 1, '3.jpg', 2, '2008-05-01', 2, now(), now()),
      (4, 'weiyixiao', '123456', '韦一笑', 1, '4.jpg', 2, '2007-01-01', 2, now(), now()),
      (5, 'changyuchun', '123456', '常遇春', 1, '5.jpg', 2, '2012-12-05', 2, now(), now()),
      (6, 'xiaozhao', '123456', '小昭', 2, '6.jpg', 3, '2013-09-05', 1, now(), now()),
      (7, 'jixiaofu', '123456', '纪晓芙', 2, '7.jpg', 1, '2005-08-01', 1, now(), now()),
      (8, 'zhouzhiruo', '123456', '周芷若', 2, '8.jpg', 1, '2014-11-09', 1, now(), now()),
      (9, 'dingminjun', '123456', '丁敏君', 2, '9.jpg', 1, '2011-03-11', 1, now(), now()),
      (10, 'zhaomin', '123456', '赵敏', 2, '10.jpg', 1, '2013-09-05', 1, now(), now()),
      (11, 'luzhangke', '123456', '鹿杖客', 1, '11.jpg', 5, '2007-02-01', 3, now(), now()),
      (12, 'hebiweng', '123456', '鹤笔翁', 1, '12.jpg', 5, '2008-08-18', 3, now(), now()),
      (13, 'fangdongbai', '123456', '方东白', 1, '13.jpg', 5, '2012-11-01', 3, now(), now()),
      (14, 'zhangsanfeng', '123456', '张三丰', 1, '14.jpg', 2, '2002-08-01', 2, now(), now()),
      (15, 'yulianzhou', '123456', '俞莲舟', 1, '15.jpg', 2, '2011-05-01', 2, now(), now()),
      (16, 'songyuanqiao', '123456', '宋远桥', 1, '16.jpg', 2, '2010-01-01', 2, now(), now()),
      (17, 'chenyouliang', '123456', '陈友谅', 1, '17.jpg', NULL, '2015-03-21', NULL, now(), now());
      
    2. 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)

    3. application.properties中引入数据库连接信息

    4. 创建对应的实体类 Emp(实体类属性采用驼峰命名)

      @Data
      @NoArgsConstructor
      @AllArgsConstructor
      public class Emp {
          private Integer id;
          private String username;
          private String password;
          private String name;
          private Short gender;
          private String image;
          private Short job;
          private LocalDate entrydate;     //LocalDate类型对应数据表中的date类型
          private Integer deptId;
          private LocalDateTime createTime;//LocalDateTime类型对应数据表中的datetime类型
          private LocalDateTime updateTime;
      }
      
    5. 准备Mapper接口 EmpMapper

      /*@Mapper注解:表示当前接口为mybatis中的Mapper接口
        程序运行时会自动创建接口的实现类对象(代理对象),并交给Spring的IOC容器管理
      */
      @Mapper
      public interface EmpMapper {
      
      }
      
  • 删除

    根据主键删除数据

    SQL语句:delete from emp where id = 17;

    接口方法:

    @Mapper
    public interface EmpMapper {
        
        //@Delete("delete from emp where id = 17")
        //public void delete();
        //以上delete操作的SQL语句中的id值写成固定的17,就表示只能删除id=17的用户数据
        //SQL语句中的id值不能写成固定数值,需要变为动态的数值
        //解决方案:在delete方法中添加一个参数(用户id),将方法中的参数,传给SQL语句
        
        /**
         * 根据id删除数据
         * @param id    用户id
         */
        @Delete("delete from emp where id = #{id}")//使用#{key}方式获取方法中的参数值
        public void delete(Integer id);
        
    }
    

    @Delete注解:用于编写delete操作的SQL语句。如果mapper接口方法形参只有一个普通类型的参数,#{…} 里面的属性名可以随便写,如:#{id}、#{value}。但是建议保持名字一致。

    测试:在单元测试类中通过@Autowired注解注入EmpMapper类型对象

    @SpringBootTest
    class SpringbootMybatisCrudApplicationTests {
        @Autowired //从Spring的IOC容器中,获取类型是EmpMapper的对象并注入
        private EmpMapper empMapper;
    
        @Test
        public void testDel(){
            //调用删除方法
            empMapper.delete(16);
        }
    
    }
    
  • 日志输入

    在Mybatis当中我们可以借助日志,查看到sql语句的执行、执行传递的参数以及执行结果。具体操作如下:

    1. 打开application.properties文件
    2. 开启mybatis的日志,并指定输出到控制台
    #指定mybatis输出日志的位置, 输出控制台
    mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    
  • 预编译SQL

    开启日志之后,我们再次运行单元测试,可以看到在控制台中输出了SQL语句信息。但是我们发现输出的SQL语句:delete from emp where id = ?,我们输入的参数16并没有在后面拼接,id的值是使用?进行占位。这种SQL语句我们称为预编译SQL。

    预编译SQL有两个优势:

    1. 性能更高:预编译SQL,编译一次之后会将编译后的SQL语句缓存起来,后面再次执行这条语句时,不会再次编译。(只是输入的参数不同)
    2. 更安全(防止SQL注入):将敏感字进行转义,保障SQL的安全性。

    SQL注入是通过操作输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法。由于没有对用户输入进行充分检查,而SQL又是拼接而成,在用户输入参数时,在参数中添加一些SQL关键字,达到改变SQL运行结果的目的,也可以完成恶意攻击。

  • 参数占位符

    在Mybatis中提供的参数占位符有两种:${...} 、#{...}

    • #
      • 执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值

      • 使用时机:参数传递,都使用#

      • $

        • 拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题
        • 使用时机:如果对表名、列表进行动态设置时使用

    注意事项:在项目开发中,建议使用#{...},生成预编译SQL,防止SQL注入安全。

  • 新增

    SQL语句:

    insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values ('songyuanqiao','宋远桥',1,'1.jpg',2,'2012-10-09',2,'2022-10-01 10:00:00','2022-10-01 10:00:00');
    

    接口方法:

    @Mapper
    public interface EmpMapper {
    
        @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")
        public void insert(Emp emp);
    
    }
    

    测试类:

    import com.itheima.mapper.EmpMapper;
    import com.itheima.pojo.Emp;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    
    @SpringBootTest
    class SpringbootMybatisCrudApplicationTests {
        @Autowired
        private EmpMapper empMapper;
    
        @Test
        public void testInsert(){
            //创建员工对象
            Emp emp = new Emp();
            emp.setUsername("tom");
            emp.setName("汤姆");
            emp.setImage("1.jpg");
            emp.setGender((short)1);
            emp.setJob((short)1);
            emp.setEntrydate(LocalDate.of(2000,1,1));
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            emp.setDeptId(1);
            //调用添加方法
            empMapper.insert(emp);
        }
    }
    
  • 主键返回

    在数据添加成功后,需要获取插入数据库数据的主键。默认情况下,执行插入操作时,是不会主键值返回的。如果我们想要拿到主键值,需要在Mapper接口中的方法上添加一个Options注解,并在注解中指定属性useGeneratedKeys=true和keyProperty="实体类属性名"。

    @Mapper
    public interface EmpMapper {
        
        //会自动将生成的主键值,赋值给emp对象的id属性
        @Options(useGeneratedKeys = true,keyProperty = "id")
        @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")
        public void insert(Emp emp);
    
    }
    

    测试:

    @SpringBootTest
    class SpringbootMybatisCrudApplicationTests {
        @Autowired
        private EmpMapper empMapper;
    
        @Test
        public void testInsert(){
            //创建员工对象
            Emp emp = new Emp();
            emp.setUsername("jack");
            emp.setName("杰克");
            emp.setImage("1.jpg");
            emp.setGender((short)1);
            emp.setJob((short)1);
            emp.setEntrydate(LocalDate.of(2000,1,1));
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            emp.setDeptId(1);
            //调用添加方法
            empMapper.insert(emp);
    
            System.out.println(emp.getDeptId());
        }
    }
    
  • 更新

    SQL语句:

    update emp set username = 'linghushaoxia', name = '令狐少侠', gender = 1 , image = '1.jpg' , job = 2, entrydate = '2012-01-01', dept_id = 2, update_time = '2022-10-01 12:12:12' where id = 18;
    

    接口方法:

    @Mapper
    public interface EmpMapper {
        /**
         * 根据id修改员工信息
         * @param emp
         */
        @Update("update emp set username=#{username}, name=#{name}, gender=#{gender}, image=#{image}, job=#{job}, entrydate=#{entrydate}, dept_id=#{deptId}, update_time=#{updateTime} where id=#{id}")
        public void update(Emp emp);
        
    }
    
  • 查询

    • 根据ID查询

      SQL语句:

      select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp;
      

      接口方法:

      @Mapper
      public interface EmpMapper {
          @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}")
          public Emp getById(Integer id);
      }
      
    • 数据封装

      我们看到查询返回的结果中大部分字段是有值的,但是deptId,createTime,updateTime这几个字段是没有值的,而数据库中是有对应的字段值的。

      原因如下:

      • 实体类属性名和数据库表查询返回的字段名一致,mybatis会自动封装。
      • 如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装。

      解决方案:

      1. 起别名

        @Select("select id, username, password, name, gender, image, job, entrydate, " +
                "dept_id AS deptId, create_time AS createTime, update_time AS updateTime " +
                "from emp " +
                "where id=#{id}")
        public Emp getById(Integer id);
        
      2. 结果映射

        通过 @Results及@Result 进行手动结果映射

        @Results({@Result(column = "dept_id", property = "deptId"),
                  @Result(column = "create_time", property = "createTime"),
                  @Result(column = "update_time", property = "updateTime")})
        @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}")
        public Emp getById(Integer id);
        
      3. 开启驼峰命名

        如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。要使用驼峰命名前提是实体类的属性与数据库表中的字段名严格遵守驼峰命名。驼峰命名规则:abc_xyz => abcXyz

        • 表中字段名:abc_xyz
        • 类中属性名:abcXyz
        # 在application.properties中添加:
        mybatis.configuration.map-underscore-to-camel-case=true
        
  • 条件查询

    • 姓名:要求支持模糊匹配
    • 性别:要求精确匹配
    • 入职时间:要求进行范围查询
    • 根据最后修改时间进行降序排序

    SQL语句:

    select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time 
    from emp 
    where name like '%张%' 
          and gender = 1 
          and entrydate between '2010-01-01' and '2020-01-01 ' 
    order by update_time desc;
    

    接口方法:

    • 方式一

      @Mapper
      public interface EmpMapper {
          @Select("select * from emp " +
                  "where name like '%${name}%' " +
                  "and gender = #{gender} " +
                  "and entrydate between #{begin} and #{end} " +
                  "order by update_time desc")
          public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
      }
      
    • 方式二(解决SQL注入风险)

      @Mapper
      public interface EmpMapper {
      
          @Select("select * from emp " +
                  "where name like concat('%',#{name},'%') " +
                  "and gender = #{gender} " +
                  "and entrydate between #{begin} and #{end} " +
                  "order by update_time desc")
          public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
      
      }
      
  • 参数名说明

    在上面我们所编写的条件查询功能中,我们需要保证接口中方法的形参名和SQL语句中的参数占位符名相同。

二、Mybatis的XML配置文件

Mybatis的开发有两种方式:注解和XML。使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就是将SQL语句写在XML配置文件中。

在Mybatis中使用XML映射文件方式开发,需要符合一定的规范:

  1. XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)

  2. XML映射文件的namespace属性为Mapper接口全限定名一致

  3. XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致。

<select>标签:就是用于编写select查询语句的。

resultType属性,指的是查询返回的单条记录所封装的类型。

  • XML配置文件实现

    • 创建XML配置文件



    • 编写XML映射文件

      xml映射文件中的dtd约束,直接从mybatis官网复制即可

      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE mapper
              PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.itheima.mapper.EmpMapper">
      
          <!--查询操作-->
          <select id="list" resultType="com.itheima.pojo.Emp">
              select * from emp
              where name like concat('%',#{name},'%')
                    and gender = #{gender}
                    and entrydate between #{begin} and #{end}
              order by update_time desc
          </select>
      

      配置:XML映射文件的namespace属性为Mapper接口全限定名。XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致。

  • MybatisX

    MybatisX是一款基于IDEA的快速开发Mybatis的插件。可以通过MybatisX快速定位:

三、Mybatis动态SQL

在页面原型中,列表上方的条件是动态的,是可以不传递的,也可以只传递其中的1个或者2个或者全部。而在我们刚才编写的SQL语句中,我们会看到,我们将三个条件直接写死了。 如果页面只传递了参数姓名name 字段,其他两个字段 性别 和 入职时间没有传递,那么这两个参数的值就是null。这个查询结果是不正确的。

正确的做法应该是:传递了参数,再组装这个查询条件;如果没有传递参数,就不应该组装这个查询条件。

比如:如果姓名输入了"张", 对应的SQL为:

select *  from emp where name like '%张%' order by update_time desc;

如果姓名输入了"张",,性别选择了"男",则对应的SQL为:

select *  from emp where name like '%张%' and gender = 1 order by update_time desc;

SQL语句会随着用户的输入或外部条件的变化而变化,我们称为:动态SQL。在Mybatis中提供了很多实现动态SQL的标签,我们学习Mybatis中的动态SQL就是掌握这些动态SQL标签。

  • 动态SQL-if

    <if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。接下来,我们就通过<if>标签来改造之前条件查询的案例。

    • 原有的SQL语句

      <select id="list" resultType="com.itheima.pojo.Emp">
              select * from emp
              where name like concat('%',#{name},'%')
                    and gender = #{gender}
                    and entrydate between #{begin} and #{end}
              order by update_time desc
      </select>
      
    • 动态SQL语句

      <select id="list" resultType="com.itheima.pojo.Emp">
              select * from emp
              where
          
                   <if test="name != null">
                       name like concat('%',#{name},'%')
                   </if>
                   <if test="gender != null">
                       and gender = #{gender}
                   </if>
                   <if test="begin != null and end != null">
                       and entrydate between #{begin} and #{end}
                   </if>
          
              order by update_time desc
      </select>
      

    当四个参数均为null事,生成的SQL语句会多一个where。该问题的解决方案:使用<where>标签代替SQL语句中的where关键字。<where>只会在子元素有内容的情况下才插入where子句,而且会自动去除子句的开头的AND或OR

    <select id="list" resultType="com.itheima.pojo.Emp">
            select * from emp
            <where>
                 <!-- if做为where标签的子元素 -->
                 <if test="name != null">
                     and name like concat('%',#{name},'%')
                 </if>
                 <if test="gender != null">
                     and gender = #{gender}
                 </if>
                 <if test="begin != null and end != null">
                     and entrydate between #{begin} and #{end}
                 </if>
            </where>
            order by update_time desc
    </select>
    
  • 更新

    完善更新员工功能,修改为动态更新员工数据信息

    • 动态更新员工信息,如果更新时传递有值,则更新;如果更新时没有传递值,则不更新
    • 解决方案:动态SQL

    修改Mapper接口:

    @Mapper
    public interface EmpMapper {
        //删除@Update注解编写的SQL语句
        //update操作的SQL语句编写在Mapper映射文件中
        public void update(Emp emp);
    }
    

    修改Mapper映射文件:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.itheima.mapper.EmpMapper">
    
        <!--更新操作-->
        <update id="update">
            update emp
            set
                <if test="username != null">
                    username=#{username},
                </if>
                <if test="name != null">
                    name=#{name},
                </if>
                <if test="gender != null">
                    gender=#{gender},
                </if>
                <if test="image != null">
                    image=#{image},
                </if>
                <if test="job != null">
                    job=#{job},
                </if>
                <if test="entrydate != null">
                    entrydate=#{entrydate},
                </if>
                <if test="deptId != null">
                    dept_id=#{deptId},
                </if>
                <if test="updateTime != null">
                    update_time=#{updateTime}
                </if>
            where id=#{id}
        </update>
    
    </mapper>
    

    同样的,需要使用<set>标签代替SQL语句中的set关键字。<set>:动态的在SQL语句中插入set关键字,并会删掉额外的逗号。(用于update语句中)

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.itheima.mapper.EmpMapper">
    
        <!--更新操作-->
        <update id="update">
            update emp
            <!-- 使用set标签,代替update语句中的set关键字 -->
            <set>
                <if test="username != null">
                    username=#{username},
                </if>
                <if test="name != null">
                    name=#{name},
                </if>
                <if test="gender != null">
                    gender=#{gender},
                </if>
                <if test="image != null">
                    image=#{image},
                </if>
                <if test="job != null">
                    job=#{job},
                </if>
                <if test="entrydate != null">
                    entrydate=#{entrydate},
                </if>
                <if test="deptId != null">
                    dept_id=#{deptId},
                </if>
                <if test="updateTime != null">
                    update_time=#{updateTime}
                </if>
            </set>
            where id=#{id}
        </update>
    </mapper>
    
  • 动态SQL-foreach

    员工删除功能(既支持删除单条记录,又支持批量删除)

    SQL语句:

    delete from emp where id in (1,2,3);
    

    Mapper接口:

    @Mapper
    public interface EmpMapper {
        //批量删除
        public void deleteByIds(List<Integer> ids);
    }
    

    XML映射文件:

    • 使用<foreach>遍历deleteByIds方法中传递的参数ids集合

      <foreach collection="集合名称" item="集合遍历出来的元素/项" separator="每一次遍历使用的分隔符" 
               open="遍历开始前拼接的片段" close="遍历结束后拼接的片段">
      </foreach>
      
      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE mapper
              PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.itheima.mapper.EmpMapper">
          <!--删除操作-->
          <delete id="deleteByIds">
              delete from emp where id in
              <foreach collection="ids" item="id" separator="," open="(" close=")">
                  #{id}
              </foreach>
          </delete>
      </mapper> 
      
  • 动态SQL-sql&include

    在xml映射文件中配置的SQL,有时可能会存在很多重复的片段,此时就会存在很多冗余的代码。我们可以对重复的代码片段进行抽取,将其通过<sql>标签封装到一个SQL片段,然后再通过<include>标签进行引用。

    • <sql>:定义可重用的SQL片段
    • <include>:通过属性refid,指定包含的SQL片段

    SQL片段: 抽取重复的代码

    <sql id="commonSelect">
     	select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp
    </sql>
    

    然后通过<include> 标签在原来抽取的地方进行引用。操作如下:

    <select id="list" resultType="com.itheima.pojo.Emp">
        <include refid="commonSelect"/>
        <where>
            <if test="name != null">
                name like concat('%',#{name},'%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entrydate between #{begin} and #{end}
            </if>
        </where>
        order by update_time desc
    </select>
    

posted @ 2023-05-05 12:24  无机呱子  阅读(14)  评论(0编辑  收藏  举报