MyBatisPlus学习笔记

一、简介

Mybatis-plus官网:https://mp.baomidou.com/

MyBatis-Plus(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生,它具有以下特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、快速入门

首先在数据库创建ssmdemo数据库,运行sql语句

DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
-- 真实开发中,version(乐观锁)、deleted(逻辑删除)、gmt_create、gmt_modified

创建springboot项目,引入依赖文件

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- 数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>
<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<!-- mybatis-plus 是自己开发,并非官方的! -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>

在resource资源路径下application.yml中配置,其中配置日志为了显示具体mabatis日志输出

# mysql 5 驱动不同 com.mysql.jdbc.Driver
# mysql 8 驱动不同com.mysql.cj.jdbc.Driver、需要增加时区的配置
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/ssmdemo?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver

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

创建po实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

创建mapper类

@Repository
public interface UserMapper extends BaseMapper<User> {
    // 所有的CRUD操作都已经编写完成了
    // 你不需要像以前的配置一大堆文件了!
}

在主启动类上扫描我们的mapper包下的所有接口(十分重要)

@MapperScan("com.mybatis.demo.mapper")
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

最后在测试类中测试

@SpringBootTest
class MybatisPlusApplicationTests {
    // 继承了BaseMapper,所有的方法都来自己父类
    // 我们也可以编写自己的扩展方法!
    @Autowired
    private UserMapper userMapper;
    
    @Test
    void contextLoads() {
    // 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
    // 查询全部用户
    List<User> users = userMapper.selectList(null);
    users.forEach(System.out::println);
    }
    
    // 测试插入
    @Test
    public void testInsert(){
        User user = new User();
        user.setName("test");
        user.setAge(3);
        user.setEmail("24736743@qq.com");
        int result = userMapper.insert(user); // 帮我们自动生成id
        System.out.println(result); // 受影响的行数
        System.out.println(user); // 发现,id会自动回填
    }
    
     // 测试更新
    @Test
    public void testUpdate(){
        User user = new User();
        // 通过条件自动拼接动态sql
        user.setId(5L);
        user.setName("123456");
        user.setAge(18);
        // 注意:updateById 但是参数是一个 对象!
        int i = userMapper.updateById(user);
        System.out.println(i);
    }
}

三、CRUD扩展

1、主键生成策略

实体类字段上 @TableId(type = IdType.xxx),其中IdTyoe的枚举类型如下

描述
AUTO数据库ID自增
NONE无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUTinsert前自行set主键值
ASSIGN_ID分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID分配UUID,主键类型为String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认default方法)

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

主键自增

  1. 实体类字段上 @TableId(type = IdType.AUTO)
  2. 数据库字段一定要是自增!

2、自动填充

创建时间、修改时间!这些个操作一遍都是自动化完成的,我们不希望手动更新!

2.1 数据库级别(工作中不允许修改数据库)

  • 首先在MySql数据库中添加两个字段create_timeupdate_time,同时设置默认值为根据当前时间戳更新
  • 在实体类User插入两个字段
private Date createTime;
private Date updateTime;

2.2 代码级别

  • 删除数据库datetime的默认值
  • 实体类字段属性上增加注解
// 字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
  • 编写处理器来处理这个注解
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // 插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill.....");
        // setFieldValByName(String fieldName, Object fieldVal, MetaObject,metaObject
        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);
    }
}

3、乐观锁

3.1 介绍

乐观锁 : 故名思意十分乐观,它总是认为不会出现问题,无论干什么不去上锁!如果出现了问题,再次更新值测试
悲观锁:故名思意十分悲观,它总是认为总是出现问题,无论干什么都会上锁!再去操作!

乐观锁实现方式

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

3.2 操作步骤

  • 给数据库增加version字段
  • 在User实体类增加对应的字段
@Version //乐观锁Version注解
private Integer version;
  • 注册组件,同时启用事务管理
// 扫描我们的 mapper 文件夹
@MapperScan("com.mybatis.demo.mapper")
@EnableTransactionManagement
@Configuration // 配置类
public class MyBatisPlusConfig {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}
  • 测试
// 测试乐观锁成功!
@Test
public void testOptimisticLocker(){
// 1、查询用户信息
User user = userMapper.selectById(1L);
// 2、修改用户信息
user.setName("test");
user.setEmail("zzzzz@163.com");
// 3、执行更新操作
userMapper.updateById(user);
}

4、普通查询操作

@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","1234567");
    map.put("age",3);
    List<User> users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}

5、分页查询

  • 配置拦截器
// 扫描我们的 mapper 文件夹
@MapperScan("com.mybatis.demo.mapper")
@EnableTransactionManagement
@Configuration // 配置类
public class MyBatisPlusConfig {
    
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }

}
  • 测试类
// 测试分页查询
@Test
public void testPage(){
    // 参数一:当前页
    // 参数二:页面大小
    // 使用了分页插件之后,所有的分页操作也变得简单的!
    Page<User> page = new Page<>(2,5);
    userMapper.selectPage(page,null);
    page.getRecords().forEach(System.out::println);
    System.out.println(page.getTotal());
}

6、逻辑删除

  • 首先在数据库中插入字段deleted,代表逻辑删除字段,设置默认为0
  • 在User实体类添加属性
@TableLogic //逻辑删除
private Integer deleted;
  • 配置application.yml
# 配置日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
  • 测试

配置好之后使用delete操作不会物理删除,而是进行逻辑删除,同时查询时自动过滤已被逻辑删除的数据

//测试删除
    @Test
    public void testDeleteById() {
        userMapper.deleteById(1L);
    }

7、条件生成器

详情请查看https://mp.baomidou.com/guide/wrapper.html

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

8、逆向工程

pom.xml引入依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>

编写代码生成器

public class CodeGenerator {

    public static void main(String[] args) {

        /** 模块名 */
        String moduleName = "bean";
        /** 基本包名 */
        String basePackage = "com.zstu";

        /** 作者 */
        String authorName = "shawn";

        /** 要生成的表名 */
        String[] tables = {"tb_student","tb_label"};

        /** table前缀 */
        String prefix = "tb_";

        /** 代码生成路径 */
        String codePath = System.getProperty("user.dir") + "/bean/src/main/java";


        //1、获取代码生成器对象
        AutoGenerator mpg = new AutoGenerator();

        //2、全局配置
        GlobalConfig gc = new GlobalConfig();
        //代码生成路径
        gc.setOutputDir(codePath);
        //作者信息
        gc.setAuthor(authorName);
        gc.setOpen(false);
        //生成ID类型
        gc.setIdType(IdType.AUTO);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setFileOverride(true);
        //去掉Servce前缀
        gc.setMapperName("%sMapper");
        //对于IDEA系列编辑器,XML 文件是不能放在 java 文件夹中的,要移到resource文件
        //多模块在配置文件要设置mapper-locations,在启动类要加上扫描的路径mapper以及spring扫描包
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setEntityName("%sEntity");
        mpg.setGlobalConfig(gc);

        //3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/intelligent_lamp?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        //4、包配置
        PackageConfig pc = new PackageConfig();
        //设置模块名
        //没有第0步时此代码必写
        pc.setModuleName(moduleName);

        //5、设置工程名
        pc.setParent(basePackage);
        //设置包名
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);


        //6、策略配置
        StrategyConfig strategy = new StrategyConfig();
        //去除前缀
        strategy.setTablePrefix(prefix);
        //数据库表名优先映射,配置
        strategy.setInclude(tables);
        //下划线转驼峰命名的策略
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //数据库命名规则
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //自动生成lombok注解
        strategy.setEntityLombokModel(true);
        //自动添加控制结构
        strategy.setRestControllerStyle(true);
        //自动添加逻辑删除策略
        strategy.setLogicDeleteFieldName("deleted");

        //7、设置自动填充策略
        TableFill gmtCreatereate = new TableFill("create_time", FieldFill.INSERT);
        //设置自动更新时间策略
        TableFill gmtModifiedodified = new TableFill("update_time", FieldFill.UPDATE);
        //获取自动填充对象
        ArrayList<TableFill> tableFills = new ArrayList<>();
        //添加填充策略
        tableFills.add(gmtCreatereate);
        tableFills.add(gmtModifiedodified);
        strategy.setTableFillList(tableFills);

        //8、设置乐观锁策略
        strategy.setVersionFieldName("version");
        //设置Restful风格
        strategy.setRestControllerStyle(true);
        //设置连接请求 http://localhost:8080/hello_id_2
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.execute();
    }
}

9、其他

Sql性能分析

四、其他错误

如果要用到xml文件的话,就必须再加两个配置,且IntelliJ Idea 出现 Could not autowire. No beans of 'xxxx' type found 的错误提示,并且发现编译生成的Classes没有xml文件夹,这时候需要进行简单配置
解决方法
首先在pom.xml文件里添加,这个是全局的,一般写在父工程里就行

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.xml</include>
      </includes>
      <filtering>false</filtering>
    </resource>
    </resources>
</build>

其次在application.yml添加配置

mybatis-plus:
  configuration: #sql日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:com/shawn/demo/mapper/xml/*.xml

五、时区处理

1、Mysql数据库

1.1 数据库与JDBC时区

数据库MySQL是存在时区的概念的,show variables like "%time_zone%";命令可以查询当前时区

#默认配置
+------------------+--------+
| Variable_name  | Value |
+------------------+--------+
| system_time_zone | CST  |
| time_zone    | SYSTEM |
+------------------+--------+

问题描述

默认CST指的是MySQL所在主机的系统时间,是中国标准时间的缩写(China Standard Time UT+8:00)。MySQL 中,如果 time_zone 为默认的 SYSTEM 值,则时区会继承为系统时区 CST,MySQL 内部将其认为是 UTC+08:00;而 jdbc 会将 CST 认为是美国中部时间,这会导致两者时间出现时区上的偏差(差8/13/14小时都可能是这个问题)

解决方法

明确指定 MySQL 数据库的时区,不使用引发误解的 CST,可以将** time_zone 改为’+8:00’**,同时 jdbc 连接串中也可以增加 serverTimezone=Asia/Shanghai

举例

#第一种方法通过代码修改
##修改mysql全局时区为北京时间,即我们所在的东8区
set global time_zone = '+8:00'; 
##修改当前会话时区,并使其立即生效
set time_zone = '+8:00'; 
flush privileges; 
#-----------------#
#第二种方法通过配置文件修改
# vim /etc/my.cnf ##在[mysqld]区域中加上
default-time_zone = '+8:00'
# /etc/init.d/mysqld restart ##重启mysql使新时区生效
#-----------------#
#这是我在用的jdbc连接
jdbc:mysql://ip:port/sql_name?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true

1.2 DateTime和TimeStamp异同

  • 默认都精确到秒
  • 时间范围不一样,TIMESTAMP 要小很多且最大范围为2038-01-19 03:14:07.999999,而datetime范围是'1000-01-01 00:00:00' to '9999-12-31 23:59:59'
  • TIMESTAMP把客户端插入的时间从当前时区转化为UTC(世界标准时间)进行存储;查询时,将其又转化为客户端当前时区进行返回。即存储的时候如果数据库换了时区,其存储的时间也会相应发生变化
  • DATETIME存储时不做任何改变,基本上是原样输入和输出

2、Java框架

2.1 LocalDateTime和Date

LocalDateTime本身不包含时区信息,它存储的是年、月、日、时分秒,纳秒这样的数字;Date存储的是一个毫秒数,准确说是从1970-01-01 00:00:00到现在经过的毫秒数,而这个毫秒数是有时区的,它存储的永远是现在针对UTC时区时的1970年零点,经过的毫秒数。

对于Date类来说,解析字符串成Date对象和格式化Date对象成字符串都会涉及时区

Date date = new Date();
// 默认是系统时区
System.out.println(date);
// 修改默认时区
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
System.out.println(date);
//输出
Fri Feb 11 16:51:58 CST 2022
Fri Feb 11 08:51:58 GMT 2022

/*-------------------*/
Date date1 = new Date();
// 默认是系统时区
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(date1));
// 设置时区
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
System.out.println(dateFormat.format(date1));
//输出
2022-02-11 08:51:58
2022-02-11 16:51:58

/*--------------------*/
String dateStr = "2022-2-11 08:00:00";
// 默认是系统时区
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date2 = dateFormat1.parse(dateStr);
System.out.println(date2.getTime());

// 设置时区
dateFormat1.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
Date date3 = dateFormat1.parse(dateStr);
System.out.println(date3.getTime());
//输出
1644566400000
1644537600000

2.2 Json传值给前端

参考:Java8 日期时间类整理

jackson也有自己的时区问题,默认情况下会将时区设置为UTC,这里仅需要在yml文件中设置全局配置即可

#时间戳统一转换
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值