零基础学会MyBatisPlus(SpringBoot环境)

MyBatis-Plus


学习视频链接,以示尊重:https://space.bilibili.com/95256449/video


一、MyBatisPlus概述

MyBatisPlus可以节省大量工作时间,所有的CRUD代码都可以自动化完成。例如,JPA 、 tk-mapper、MyBatisPlus都是目前比较流行的框架。

相关特性:(copy自官网)

无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作, BaseMapper

强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分

CRUD 操作,更有强大的条件构造器,满足各类使用需求, 以后简单的CRUD操作,不再用自己编写。

支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配

置,完美解决主键问题

支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大

的 CRUD 操作支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、

Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用(自动帮你生成代码)

内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同

于普通 List 查询

分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、

Postgre、SQLServer 等多种数据库

内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢

查询

内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误

操作


二、快速使用

2.1 导入依赖
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>

注意:使用 mybatis-plus 可以节省我们大量的代码,尽量不要同时导入 mybatis 和 mybatis-plus,存在版本的差异。

2.2 配置数据库信息
spring.datasource.username=xxxxxxx
spring.datasource.password=xxxxxxx
spring.datasource.url=jdbc:mysql://xxx:3306/mybatis_plus?rewriteBatchedStatements=true&\
    useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2.3 使用
2.3.1 pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
2.3.2 mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
    
    
}

注意:需要在主启动类上去扫描mapper包下的所有接口

@MapperScan("com.xingyu.mybatisplus.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
    
    
    public static void main(String[] args) {
    
    
     	SpringApplication.run(MybatisPlusApplication.class, args);
    }
}
2.3.3 测试类测试
@SpringBootTest
class MybatisPlusApplicationTests {
    
    

    // 继承了BaseMapper,所有的方法都来自己父类,也可以编写自己的扩展方法。
    @Autowired
    private UserMapper userMapper;

	@Test
	void contextLoads() {
    
    
        // 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }
}


//控制台输出:
User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)

三、配置日志

背景:Mybatis-Plus 使用过程中,所有的 SQL 执行语句是不可见的,通过打印日志可以进行查看。

配置日志:

#mybatis-plus日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

输出结果,会显示出对应的 SQL 语句:

==>  Preparing: SELECT id,name,age,email FROM user 
==> Parameters: 
<==    Columns: id, name, age, email
<==        Row: 1, Jone, 18, [email protected]
<==        Row: 2, Jack, 20, [email protected]
<==        Row: 3, Tom, 28, [email protected]
<==        Row: 4, Sandy, 21, [email protected]
<==        Row: 5, Billie, 24, [email protected]
<==      Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7d401cdc]
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])

四、CRUD及其扩展

4.1 插入操作
@Test 
public void testInsert(){
    
     
    User user = new User(); 
    user.setName("刘星宇"); 
    user.setAge(22); 
    user.setEmail("[email protected]"); 
    int result = userMapper.insert(user); // 插入新用户时,会自动生成id 
    System.out.println(result); // 返回结果是受影响的行数 
    System.out.println(user); // id会自动回填 
}

//输出结果:
==>  Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? ) 
==> Parameters: 1310120436132016129(Long), 刘星宇(String), 22(Integer), 931318132@qq.com(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@f017dd0]
1
User(id=1310120436132016129, name=刘星宇, age=22, email=931318132@qq.com)

注意:这时数据库插入的 id 的默认值为:全局的唯一id。

4.2 主键生成策略

分布式系统唯一id生成:https://www.cnblogs.com/haoxinyue/p/5208136.html

1、默认 ID_WORKER 全局唯一id

2、雪花算法

snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。

3、主键自增

  • 实体类字段上添加注解:

    @TableId(type = IdType.AUTO) 
    
  • 数据库建表时,对应地字段一定要设置为自增

补充:@TableId 注解的 type 属性的取值是一个枚举类 IdType ,其可取值还有多种:

public enum IdType {
    
    
    AUTO(0),
    NONE(1),
    INPUT(2),
    ID_WORKER(3),
    UUID(4),
    ID_WORKER_STR(5);

    private int key;

    private IdType(int key) {
    
    
        this.key = key;
    }

    public int getKey() {
    
    
        return this.key;
    }
}
4.3 更新操作
// 测试更新 
@Test 
public void testUpdate(){
    
     
    User user = new User(); // 通过条件自动拼接动态sql 
    user.setId(6L); 
    user.setName("老皮皮"); 
    user.setAge(23); // 注意:updateById 但是参数是一个 对象! 
    int i = userMapper.updateById(user); 
    System.out.println(i);
}

//输出结果:
==> Parameters: 老皮皮(String), 23(Integer), 5(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@19ae36f4]
1
4.4 自动填充

在很多情况下,数据库中的表有类似“创建时间”、“修改时间”的字段,这些字是需要自动填充的,不希望手动操作。

4.4.1 数据库级别

注意:这种方式工作中是不建议使用的,因为工作中不允许修改数据库。

1、在表中新增字段:create_time、update_time

注意选择默认值为当前时间。即:CURRENT_TIMESTAMP

2、同步对应的 pojo

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;
    private Date createTime;
    private Date updateTime;
}

3、测试

4.4.2 代码级别

1、删除数据库的默认值、更新操作

2、实体类字段属性上需要增加注解

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

3、编写处理器来处理这个注解

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    

    @Override
    public void insertFill(MetaObject metaObject) {
    
    
        log.info("start insert fill ....");
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
    
    
        log.info("start update fill ....");
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

4、测试插入操作和更新操作后对应字段的变化

4.5 乐观锁

乐观锁:顾名思义十分乐观,它总是认为不会出现问题,无论干什么不去上锁。如果出现了问题,再次更新值测试

悲观锁:顾名思义十分悲观,它总是认为总是出现问题,无论干什么都会上锁,再去操作

乐观锁实现思想:

  • 取出记录时,获取当前 version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

使用:

1、数据库表中增加一个 version 字段并设置其默认值为1

2、同步对应的 pojo

@Version //乐观锁注解
private Integer version;

3、注册组件

@MapperScan("com.xingyu.mybatisplus.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
    
    
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
    
    
        return new OptimisticLockerInterceptor();
    }
}

4、测试乐观锁

4.6 查询操作
   // 测试查询
    @Test
    public void testSelectById(){
    
    
	    User user = userMapper.selectById(1L);
	    System.out.println(user);
	}
	// 测试批量查询!
    @Test
    public void testSelectByBatchId(){
    
    
	    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
	    users.forEach(System.out::println);
	}
	// 按条件查询之一使用map操作
    @Test
    public void testSelectByBatchIds(){
    
    
	    HashMap<String, Object> map = new HashMap<>();
	    // 自定义要查询
        map.put("name","刘星宇");
        map.put("age",22);
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
	}
4.7 分页查询

分页的方式有很多种:

  • 原始的 limit 进行分页
  • pageHelper 第三方插件
  • mybatisplus内置分页插件

使用方式:

1、配置拦截器组件

@MapperScan("com.xingyu.mybatisplus.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
    
    
    //乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
    
    
        return new OptimisticLockerInterceptor();
    }

    //分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
    
    
        return new PaginationInterceptor();
    }
}

2、使用Page对象

@Test
public void testPage(){
    
    
    // 参数一:当前页
    // 参数二:页面大小
	Page<User> page = new Page<>(1,5);
	userMapper.selectPage(page, null);

    page.getRecords().forEach(System.out::println);
    System.out.println(page.getTotal());
}
4.8 删除操作
// 测试删除 
@Test 
public void testDeleteById(){
    
     
    userMapper.deleteById(1240620674645544965L); 
}

// 通过id批量删除 
@Test 
public void testDeleteBatchId(){
    
    
    userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L,124062067464554496 2L)); 
}

// 通过map删除(条件删除)
@Test 
public void testDeleteMap(){
    
     
    HashMap<String, Object> map = new HashMap<>(); 
    map.put("name","刘星宇"); 
    userMapper.deleteByMap(map);
}
4.9 逻辑删除

**物理删除 :**从数据库中直接移除

**逻辑删除 :**在数据库中没有被移除,而是通过一个“字段”来表示是否删除。例如: deleted = 0 => deleted = 1

注意:

  • 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除
  • 如果需要频繁查出来看就不应使用逻辑删除,而是以一个状态去表示
  • 进行的是删除操作,但是实际执行的是更新操作
  • 查询的时候会自动过滤掉被逻辑删除的记录
  • 管理员可以查看被删除的记录,防止数据的丢失,类似于回收站机制

使用方式:

1、在数据表中增加一个 deleted 字段

设置默认值为0,表示没有被删除。

2、实体类中增加属性

@TableLogic //逻辑删除
private Integer deleted;

3、配置

# 配置逻辑删除 
mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
4.10 性能分析插件

背景:应对慢 SQL 查询,可设置过期时间,一旦超过该时间就抛出异常。使用性能分析插件,可以帮助我们提高效率

注意:新版mybatisplus官方移除了该插件,建议使用第三方插件进行处理(druid…)。

4.11 *条件构造器

条件构造器,即Wrapper。是mybatisplus中十分重要的概念。写一些复杂的 SQL 就可以使用它来替代。

应用举例:

@Test
void contextLoads() {
    
    
    // 查询name不为空的用户,并且邮箱不为空的用户,并且年龄大于等于12
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.isNotNull("name")
           .isNotNull("email")
           .ge("age",12);
    userMapper.selectList(wrapper).forEach(System.out::println);
}


@Test
void test2(){
    
    
    // 查询名字是Tom的一个用户
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("name","Tom");
    // selectOne方法查询一条记录,如果出现多个结果可以使用List 或者 Map
    User user = userMapper.selectOne(wrapper);
    System.out.println(user);
}


// between
@Test 
void test3(){
    
     
    // 查询年龄在 20 ~ 30 岁之间的用户 
    QueryWrapper<User> wrapper = new QueryWrapper<>(); 
    wrapper.between("age",20,30); // 区间 
    Integer count = userMapper.selectCount(wrapper);// 查询结果数 
    System.out.println(count); 
}


// 模糊查询 
@Test 
void test4(){
    
     
    QueryWrapper<User> wrapper = new QueryWrapper<>(); 
    // notLike表示‘name’字段中不包含‘e’的记录
    // 表示左或右模糊查询 %t、t%
    wrapper .notLike("name","e") 
        .likeRight("email","t");  // 相当于t%,查询以t开头的
    List<Map<String, Object>> maps = userMapper.selectMaps(wrapper); 
    maps.forEach(System.out::println); 
}


// 子查询
@Test 
void test5(){
    
     
    QueryWrapper<User> wrapper = new QueryWrapper<>(); 
    // id 在子查询中查出来 
    wrapper.inSql("id","select id from user where id<3"); 
    List<Object> objects = userMapper.selectObjs(wrapper); 
    objects.forEach(System.out::println); 
}


// 排序
@Test 
void test6(){
    
     
    QueryWrapper<User> wrapper = new QueryWrapper<>(); 
    // 通过id进行排序
    wrapper.orderByAsc("id"); 
    List<User> users = userMapper.selectList(wrapper); 
    users.forEach(System.out::println); 
}

官方文档中还有很多类似语法:https://baomidou.com/guide/wrapper.html#abstractwrapper

4.12 代码自动生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

1、导入依赖(3.0.3后的mybatisplus需要手动导入依赖)

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
</dependency>

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
</dependency>

2、编写生成器

package com.xingyu.mybatisplus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;

/**
 * @Author 刘星宇
 * @Date 2020/9/27 17:59
 */
public class CodeGenerator {
    
    
    public static void main(String[] args) {
    
    
        AutoGenerator mpg = new AutoGenerator();
        // 1.全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("xingyu");
        gc.setOpen(false);
        gc.setFileOverride(false); // 是否覆盖
        gc.setServiceName("%sService"); // 去Service的I前缀
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 2.数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://xxx:3306/mybatis_plus?rewriteBatchedStatements=true&" +
                "useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("xxx");
        dsc.setPassword("xxx");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 3.包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("mybatisplus"); //模块名
        pc.setParent("com.xingyu");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        //4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        // 设置要映射的表名
        strategy.setInclude("user");
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);    // 自动lombok;
        strategy.setLogicDeleteFieldName("deleted"); // 逻辑删除字段

        // 自动填充配置
        TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate); //创建时间的自动填充
        tableFills.add(gmtModified); //更新时间的自动填充
        strategy.setTableFillList(tableFills);

        // 乐观锁
        strategy.setVersionFieldName("version");
        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2
        mpg.setStrategy(strategy);


        mpg.execute(); //执行
    }

}

3、运行该生成器,自动生成mapper、controller、service、entity的代码,偷懒神器

猜你喜欢

转载自blog.csdn.net/qq_40585800/article/details/108833955