一、什么是mybatis-plus
升级版的mybatis,目的是让mybatis更易于使用, 用官方的话说“为简化而生”
官网:
https://baomidou.com/
二、初体验
1.准备数据库脚本
数据库 Schema 脚本如下:
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)
);
其对应的数据库 Data 脚本如下:
DELETE FROM user;
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’);
2.初始化工程
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xnx</groupId>
<artifactId>mp280</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mp280</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/t280?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
启动类,指定mapper接口的位置
package com.xnx.mp280;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.xnx.mp280.mapper")
@SpringBootApplication
public class Mp280Application {
public static void main(String[] args) {
SpringApplication.run(Mp280Application.class, args);
}
}
3.编码
编写实体类 User.java
package com.xnx.mp280.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.util.Date;
@Data
public class User {
// @TableId(type = IdType.INPUT)
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 lastModifyTime;
}
编写 Mapper 包下的 UserMapper
接口
package com.xnx.mp280.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xnx.mp280.model.User;
public interface UserMapper extends BaseMapper<User> {
}
4.开始使用
添加测试类,进行功能测试:
package com.xnx.mp280;
import com.xnx.mp280.mapper.UserMapper;
import com.xnx.mp280.model.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class SampleTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
@Test
public void testInsert() {
User user = new User();
user.setAge(20);
user.setEmail("xxnnxx@qq.com");
user.setName("xnx");
// user.setId(66L);
int insert = userMapper.insert(user);
System.out.println(insert);
}
@Test
public void testUpdate() {
User user = new User();
user.setId(1612365677631373314L);
//ID用于定位sql,其他的列段设置几个就修改几个,没有设置的则保留原来的值
user.setName("xnx");
user.setAge(19);
int i = userMapper.updateById(user);
System.out.println(i);
}
}
三、日志
application.properties
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
在开发中将sql语句打印到控制台,以便于调试
四、主键生成策略
雪花算法
默认的主键生策略,如果需要保存的实体对象中没有指定的主键值,则默认使用雪花算法来生成
自增ID
数据库的字段必须是配置了自增
对应的实体的主键字段加入自增注解: @TableId(type = IdType.AUTO)
其他类型:
public enum IdType {
AUTO(0), //自动增长
NONE(1), //未设置主键
INPUT(2), //手动输入
ASSIGN_ID(3), //雪花算法
ASSIGN_UUID(4); //排除到下划线的UUID,32位长度
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
测试代码
package com.xnx.mp280.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.util.Date;
@Data
public class User {
// @TableId(type = IdType.INPUT)
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 lastModifyTime;
}
SampleTest.java如上
加注解自动增长(不是雪花算法):
Input:自己手动赋值为准
五、更新
通过主键更新
SampleTest.java见上
六、自动填充
在数据表的设计中,经常需要加一些字段,如:创建时间,最后修改时间等,此时可以使用mybatis-plus来帮我们进行自动维护
在自动填充有两种方式:
1、通过数据库完成自动填充
注意:
生成时间:不需要根据当前时间戳更新
最后修改时间:需要根据当前时间戳更新
测试代码如上
记得yaml中最后一行注释掉
2、使用程序完成自动填充
将数据库中的自动维护功能取消:
第一步:实体类中加入注解 见上User
第二步:编写处理类
package com.xnx.mp280.component;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("lastModifyTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
//this.setFieldValByName("createTime",new Date(), metaObject);
this.setFieldValByName("lastModifyTime", new Date(), metaObject);
}
}
测试代码如上