当前位置 博文首页 > 盛夏温暖流年:MyBatis Plus 的使用之入门

    盛夏温暖流年:MyBatis Plus 的使用之入门

    作者:[db:作者] 时间:2021-07-13 19:01

    一. 什么是 MyBatis Plus

    MyBatis Plus 是国内人员开发的 MyBatis 增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。它类似于JPA,对通用的 CRUD 方法进行封装,在进行简单的单表操作时,我们不需要再写xml,而是直接调用这些方法即可,使开发更加简单顺畅。

    MyBatis Plus 的核心功能有:支持通用的 CRUD代码生成器条件构造器

    通用 CRUD:定义好 Mapper 接口后,只需要继承 BaseMapper<T>接口即可获得通用的增删改查功能,无需编写任何接口方法与配置文件.

    条件构造器:通过 EntityWrapper<T> (实体包装类),可以用于拼接 SQL 语句,并且支持排序、分组查询等复杂的 SQL。

    代码生成器:支持策略配置与全局配置,比 MyBatis 的代码生成更好用。

    二. Spring Boot 整合 MyBatis Plus

    正如官方所说,MyBatis Plus 在 MyBatis 的基础上只做增强不做改变,因此其与 Spring Boot 的整合亦非常简单,只需把 MyBatis 的依赖换成 MyBatis Plus 的依赖即可。

    1.在pom.xml中加入对应依赖

    <!-- MyBatis Plus 依赖 -->
      <dependency>
          <groupId>com.baomidou</groupId>
          <artifactId>mybatis-plus</artifactId>
          <version>2.3</version>
      </dependency>
    

    2.在 application.properties 添加配置,打开驼峰到下划线的映射

    mybatis-plus.configuration.map-underscore-to-camel-case = true

    3.创建用户表

    #创建用户表
    CREATE TABLE user (
        id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键',
        name VARCHAR(30) DEFAULT NULL COMMENT '姓名',
        age INT(11) DEFAULT NULL COMMENT '年龄',
        address_id BIGINT(20) DEFAULT NULL COMMENT '家庭住址id',
        create_time DATETIME DEFAULT NULL COMMENT '创建时间'
    )  ENGINE=INNODB CHARSET=UTF8;
    

    4.新建与 user 表映射的实体类

    // @Data 是 Lombok 的注解,是一种 Java 实用工具,会为我们自动生成 set 和 get 方法
    @Data
    public class User {
        private Long id;
        private String name;
        private Integer age;
        private Long addressId;
        private Date createTime;
    }
    

    5.dao 层中创建 mapper 接口,继承 MyBatis Plus 的 BaseMapper

    public interface UserMapper extends BaseMapper<User> {
    
    }
    

    6.启动类添加 @MapperScan 注解,配置需要扫描的 dao 层接口

    @MapperScan("org.demo.dao")
    @SpringBootApplication
    public class MyBatisPlusDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MyBatisPlusDemoApplication.class, args);
        }
    }
    

    7.编写测试类

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class MyBatisPlusDemoApplicationTests {
    
        @Resource
        private UserMapper userMapper;
        
        @Test
        public void select(){
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        }
    
    }
    

    三. MyBatis Plus 的常用 CURD

    1.insert 操作
    	User user = new User();
        user.setAge(3);
        user.setAddressId(10L);
        user.setCreateTime(new Date());
        userMapper.insert(user);
        System.out.println("用户id为:" + user.id);
    
    2.update 操作
    	User user = new User();
    	user.setId(1L);
        user.setAge(13);
    	//根据 id 进行更新,没有传值的属性就不会更新
        userMapper.updateById(user);
    
    3.select 操作

    (1). 根据 id 查询:

    	User user = userMapper.selectById(1L);
    

    (2). 根据条件查询单条:

    	User user = new User();
    	user.setId(1L);
    	//若是数据库中符合传入的条件的记录有多条,那就不能用这个方法,会报错
    	User user = userMapper.selectOne(user);
    

    (3). 根据条件查询多条:

    	Map<String,Object> columnMap = new HashMap<>();
    	// 表中的列名
    	columnMap.put("age",13);
    	List<User> users = userMapper.selectByMap(columnMap);
    

    (4). 通过id批量查询:

    	List<Long> idList = new ArrayList<>();
    	idList.add(1L);
    	idList.add(2L);
    	idList.add(3L);
    	List<User> users = userMapper.selectBatchIds(idList);
    
    4.delete 操作

    (1). 根据 id 删除:

    	userMapper.deleteById(1L);
    

    (2). 根据条件删除:

    	Map<String,Object> columnMap = new HashMap<>();
    	columnMap.put("age", 18);
    	userMapper.deleteByMap(columnMap);
    

    (3). 根据id批量删除:

     	List<Integer> idList = new ArrayList<>();
     	idList.add(1);
     	idList.add(2);
     	userMapper.deleteBatchIds(idList);
    

    四. 条件构造器

    1.allEq

    全部 eq (或个别 isNull)

    allEq({id:1,name:"老王",age:null})  --->  id = 1 and name = '老王' and age is null
    
    allEq({id:1,name:"老王",age:null}, false)  --->  id = 1 and name = '老王'
    

    2.eq

    等于 =

    eq("name", "老王")  --->  name = '老王'
    

    3.ne

    不等于 <>

    ne("name", "老王")  --->  name <> '老王'
    

    4.gt

    大于 >

    gt("age", 18)  --->  age > 18
    

    5.ge

    大于等于 >=

    ge("age", 18) ---> age >= 18
    

    6.lt
    小于 <

    lt("age", 18) ---> age < 18
    

    7.le
    小于等于 <=

    le("age", 18) ---> age <= 18
    

    8.between

    BETWEEN 值1 AND 值2

    between("age", 18, 30) ---> age between 18 and 30
    

    9.notBetween

    NOT BETWEEN 值1 AND 值2

    notBetween("age", 18, 30) ---> age not between 18 and 30
    

    10.like

    LIKE ‘%值%’

    like("name", "王") ---> name like '%王%'
    

    10.notLike

    NOT LIKE ‘%值%’

    notLike("name", "王") ---> name not like '%王%'
    

    11.likeLeft

    LIKE ‘%值’

    likeLeft("name", "王") ---> name like '%王'
    

    12.likeRight

    LIKE ‘值%’

    likeRight("name", "王") ---> name like '王%'
    

    13.isNull

    字段 IS NULL

    isNull("name") ---> name is null
    

    14.isNotNull

    字段 IS NOT NULL

    isNotNull("name") ---> name is not null
    

    15.in

    字段 IN (value.get(0), value.get(1), …)

    in("age",{1,2,3}) ---> age in (1,2,3)
    

    字段 IN (v0, v1, …)

    in("age", 1,
    
    下一篇:没有了