目录
1.什么是mybatis-plus
升级版的mybatis,目的是让mybatis更易于使用, 用官方的话说“为简化而生” 官网: MyBatis-Plus
2.初体验
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.ycx
</groupId>
-
<artifactId>mptest01
</artifactId>
-
<version>0.0.1-SNAPSHOT
</version>
-
<name>mptest01
</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:
server.port=8080
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/oapro?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接口的位置
-
@
MapperScan(
"com.ycx.mptest01.**")
-
@
SpringBootApplication
-
public
class
Mptest01Application {
-
-
public
static
void
main(
String[] args) {
-
SpringApplication.
run(
Mptest01Application.
class, args);
-
}
-
-
}
3.编码
编写实体类 User.java
-
import lombok.
Data;
-
-
@
Data
-
public
class
User {
-
private
Long id;
-
private
String name;
-
private
Integer age;
-
private
String email;
-
}
编写 Mapper 包下的 UserMapper
接口
-
import com.
baomidou.
mybatisplus.
core.
mapper.
BaseMapper;
-
import com.
ycx.
mptest01.
model.
User;
-
import org.
springframework.
stereotype.
Repository;
-
-
@
Repository
-
public interface
UserMapper
extends
BaseMapper<
User> {
-
-
}
4.开始使用
添加测试类,进行功能测试:
-
package com.
ycx.
mptest01;
-
-
import com.
ycx.
mptest01.
mapper.
UserMapper;
-
import com.
ycx.
mptest01.
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);
-
}
-
-
}
3.日志
application.properties
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
在开发中将sql语句打印到控制台,以便于调试
4.主键生成策略
雪花算法
默认的主键生策略,如果需要保存的实体对象中没有指定的主键值,则默认使用雪花算法来生成
自增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.
ycx.
mptest01.
model;
-
-
import com.
baomidou.
mybatisplus.
annotation.
IdType;
-
import com.
baomidou.
mybatisplus.
annotation.
TableId;
-
import lombok.
Data;
-
-
@
Data
-
public
class
User {
-
// @TableId(type = IdType.AUTO) 数据库自增
-
// @TableId(type = IdType.ASSIGN_ID) 默认雪花算法
-
@
TableId(type =
IdType.
INPUT)
// 程序员自己控制
-
private
Long id;
-
private
String name;
-
private
Integer age;
-
private
String email;
-
}
SampleTest.java
-
@
Test
-
public
void
testInsert(
) {
-
User user =
new
User();
-
user.
setAge(
18);
-
user.
setEmail(
"javaxl@qq.com");
-
user.
setName(
"javaxl");
-
// user.setId(66L); // 程序员自己控制
-
userMapper.
insert(user);
-
}
测试结果如下
5.更新
通过主键更新
SampleTest.java
-
@
Test
-
public
void
testUpdate(
) {
-
User user =
new
User();
-
user.
setId(6L);
-
//ID用于定位sql,其他的列段设置几个就修改几个,没有设置的则保留原来的值
-
user.
setName(
"小李飞刀");
-
user.
setAge(
22);
-
int i = userMapper.
updateById(user);
-
System.
out.
println(i);
-
}
6.自动填充
在数据表的设计中,经常需要加一些字段,如:创建时间,最后修改时间等,此时可以使用mybatis-plus来帮我们进行自动维护
在自动填充有两种方式:
一: 通过数据库完成自动填充
注意:
生成时间:不需要根据当前时间戳更新
最后修改时间:需要根据当前时间戳更新
测试代码如下
-
@
Test
-
public
void
testInsert(
) {
-
User user =
new
User();
-
user.
setAge(
18);
-
user.
setEmail(
"javaxl@qq.com");
-
user.
setName(
"javaxl");
-
userMapper.
insert(user);
-
}
-
@Data
-
public
class
User {
-
// @TableId(type = IdType.AUTO) 数据库自增
-
// @TableId(type = IdType.ASSIGN_ID) 默认雪花算法
-
// @TableId(type = IdType.INPUT) // 程序员自己控制
-
private Long id;
-
private String name;
-
private Integer age;
-
private String email;
-
-
//在代码中同步加入创建时间和最后修改时间的维护
-
private Date createTime;
-
private Date lastModifiedTime;
-
}
结果如下:
完成后可以通过新增或更新
二:使用程序完成自动填充
将数据库中的自动维护功能取消:
第一步:实体类中加入注解
-
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.AUTO) 数据库自增
-
// @TableId(type = IdType.ASSIGN_ID) 默认雪花算法
-
// @TableId(type = IdType.INPUT) // 程序员自己控制
-
private
Long id;
-
private
String name;
-
private
Integer age;
-
private
String email;
-
-
//在代码中同步加入创建时间和最后修改时间的维护
-
// private Date createTime;
-
// private Date lastModifiedTime;
-
-
//表明在插入时自动维护字段
-
@
TableField(fill =
FieldFill.
INSERT)
-
private
Date createTime;
-
//表明在插入和更新时自动维护字段
-
@
TableField(fill =
FieldFill.
INSERT_UPDATE)
-
private
Date lastModifiedTime;
-
}
第二步:编写处理类
-
import com.
baomidou.
mybatisplus.
core.
handlers.
MetaObjectHandler;
-
import org.
apache.
ibatis.
reflection.
MetaObject;
-
import org.
springframework.
stereotype.
Component;
-
-
import java.
util.
Date;
-
-
// 不要忘了处理器是spring的组件
-
@
Component
-
public
class
AutoFillHandler implements
MetaObjectHandler {
-
@
Override
-
public
void
insertFill(
MetaObject metaObject) {
-
this.
setFieldValByName(
"createTime",
new
Date(), metaObject);
-
this.
setFieldValByName(
"lastModifiedTime",
new
Date(), metaObject);
-
-
}
-
-
@
Override
-
public
void
updateFill(
MetaObject metaObject) {
-
//this.setFieldValByName("createTime",new Date(), metaObject);
-
this.
setFieldValByName(
"lastModifiedTime",
new
Date(), metaObject);
-
}
-
}
测试代码如下
-
@
Test
-
public
void
testInsert(
) {
-
User user =
new
User();
-
user.
setAge(
18);
-
user.
setEmail(
"javaxl@qq.com");
-
user.
setName(
"javaxl");
-
userMapper.
insert(user);
-
}
-
-
@
Test
-
public
void
testUpdate(
) {
-
User user =
new
User();
-
user.
setId(1611736686478331905L);
-
//ID用于定位sql,其他的列段设置几个就修改几个,没有设置的则保留原来的值
-
user.
setName(
"小李飞刀");
-
user.
setAge(
22);
-
int i = userMapper.
updateById(user);
-
System.
out.
println(i);
-
}
完成后可以通过新增或更新。
转载:https://blog.csdn.net/weixin_65808248/article/details/128757265