Mybaits-Plus实战 公共字段填充(七)

MyBatis-Plus 公共字段填充示例

脚本初始化

schema-h2.sql

1
2
3
4
5
6
7
8
9
10
11
12
13
-- noinspection SqlNoDataSourceInspectionForFile

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 '邮箱',
operator VARCHAR(30) NULL DEFAULT NULL COMMENT '操作员',
PRIMARY KEY (id)
);

data-h2.sql

1
2
3
4
DELETE FROM user;

INSERT INTO user (id, name, age, email, operator)
VALUES (1, 'Jone', 18, 'test1@baomidou.com', 'test');

添加依赖

父模块 pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.ray</groupId>
<artifactId>mybatis-plus-study</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>

<name>mybatis-plus-study</name>
<description>Demo project for Spring Boot</description>

<modules>
<module>mybatis-plus-study-quickstart-springmvc</module>
<module>mybatis-plus-study-quickstart-springboot</module>
<module>mybatis-plus-study-generator</module>
<module>mybatis-plus-study-crud</module>
<module>mybatis-plus-study-wrapper</module>
<module>mybatis-plus-study-pagination</module>
<module>mybatis-plus-study-auto-fill-metainfo</module>
</modules>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mybatisplus.version>3.0.1</mybatisplus.version>
</properties>

<dependencies>
<!--Mybatis-Plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.version}</version>
</dependency>

<!--Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--H2-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<!--Test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

子模块 pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>mybatis-plus-study-auto-fill-metainfo</artifactId>

<description>MyBatis-Plus 公共字段填充示例</description>

<parent>
<groupId>com.ray</groupId>
<artifactId>mybatis-plus-study</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

</project>

实体类

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.ray.mybatisplusstudyautofillmetainfo.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* @author Ray
* @date 2018/10/8
* 用户实体
*/
@Data
@TableName(value = "user")
@NoArgsConstructor
@AllArgsConstructor
public class User {

private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT_UPDATE)
private String operator;
}

说明

  1. FieldFill fill():字段自动填充策略
  2. FieldFill:字段填充策略枚举类
  3. INSERT_UPDATE:插入和更新填充字段

数据访问层

UserMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.ray.mybatisplusstudyautofillmetainfo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ray.mybatisplusstudyautofillmetainfo.entity.User;
import org.apache.ibatis.annotations.Mapper;

/**
* @author Ray
* @date 2018/10/8
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}

说明

使用@Mapper注解可以不用添加MapperScan(basePackages = ''),但必须在每个访问层添加,比较麻烦。

字段填充控制器

MyMetaObjectHandler.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.ray.mybatisplusstudyautofillmetainfo.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
* @author Ray
* @date 2018/10/8
* 填充器
*/
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ...");
metaObject.setValue("operator", "Jerry");
}

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

说明

  1. void insertFill:插入元对象字段填充(用于插入时对公共字段的填充)
  2. void updateFill:更新元对象字段填充(用于更新时对公共字段的填充)

配置文件

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:test
username: root
password: root
schema: classpath:db/schema-h2.sql
data: classpath:db/data-h2.sql

mybatis-plus:
global-config:
db-config:
id-type: id_worker
capital-mode: true
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

说明

  1. idType:全局默认主键类型
  2. capitalMode:是否开启大写命名,默认不开启
  3. log-impl:其中logImpl的属性就是标准控制台输出类,怎么找到这个标准控制台输出类呢?其实很简单,logImpl是Class类型,泛型为? extends Log,也就是接收一个Log实现类,然后寻找Log实现类即可,其中StdOutImpl就是Log实现类,表示在控制台输出日志的

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.ray.mybatisplusstudyautofillmetainfo;

import com.ray.mybatisplusstudyautofillmetainfo.entity.User;
import com.ray.mybatisplusstudyautofillmetainfo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
* 自动填充测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class MybatisPlusStudyAutoFillMetainfoApplicationTests {

@Autowired
private UserMapper userMapper;

@Test
public void test() {

User user = new User(null, "Tom", 1, "tom@qq.com", null);
userMapper.insert(user);
log.info("query user:{}", userMapper.selectById(user.getId()));
User beforeUser = userMapper.selectById(1L);
log.info("before user:{}", beforeUser);
beforeUser.setAge(12);
userMapper.updateById(beforeUser);
log.info("query user:{}", userMapper.selectById(1L));
}

}

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
2018-10-08 17:21:44.708  INFO 912 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2018-10-08 17:21:44.931 INFO 912 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-10-08 17:21:44.963 INFO 912 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [db/schema-h2.sql]
2018-10-08 17:21:44.982 INFO 912 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [db/schema-h2.sql] in 18 ms.
2018-10-08 17:21:44.989 INFO 912 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [db/data-h2.sql]
2018-10-08 17:21:44.993 INFO 912 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [db/data-h2.sql] in 4 ms.
___ ___ ______ _ _ ______ _
| \/ | | ___ \ | | (_) | ___ \| |
| . . | _ _ | |_/ / __ _ | |_ _ ___ | |_/ /| | _ _ ___
| |\/| || | | || ___ \ / _` || __|| |/ __| | __/ | || | | |/ __|
| | | || |_| || |_/ /| (_| || |_ | |\__ \ | | | || |_| |\__ \
\_| |_/ \__, |\____/ \__,_| \__||_||___/ \_| |_| \__,_||___/
__/ |
|___/ 3.0.1

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Property 'mapperLocations' was not specified or no matching resources found
2018-10-08 17:21:46.047 INFO 912 --- [ main] lusStudyAutoFillMetainfoApplicationTests : Started MybatisPlusStudyAutoFillMetainfoApplicationTests in 6.674 seconds (JVM running for 8.264)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@53d6e959] was not registered for synchronization because synchronization is not active
2018-10-08 17:21:46.602 INFO 912 --- [ main] c.r.m.handler.MyMetaObjectHandler : start insert fill ...
JDBC Connection [HikariProxyConnection@1747862060 wrapping conn0: url=jdbc:h2:mem:test user=ROOT] will not be managed by Spring
==> Preparing: INSERT INTO user ( ID, NAME, AGE, EMAIL, operator ) VALUES ( ?, ?, ?, ?, ? )
==> Parameters: 1049228348251709442(Long), Tom(String), 1(Integer), tom@qq.com(String), Jerry(String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@53d6e959]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@58a3d521] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1472904643 wrapping conn0: url=jdbc:h2:mem:test user=ROOT] will not be managed by Spring
==> Preparing: SELECT ID,NAME,AGE,EMAIL,operator FROM user WHERE ID=?
==> Parameters: 1049228348251709442(Long)
<== Columns: ID, NAME, AGE, EMAIL, OPERATOR
<== Row: 1049228348251709442, Tom, 1, tom@qq.com, Jerry
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@58a3d521]
2018-10-08 17:21:46.704 INFO 912 --- [ main] lusStudyAutoFillMetainfoApplicationTests : query user:User(id=1049228348251709442, name=Tom, age=1, email=tom@qq.com, operator=Jerry)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@255d9277] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@501301044 wrapping conn0: url=jdbc:h2:mem:test user=ROOT] will not be managed by Spring
==> Preparing: SELECT ID,NAME,AGE,EMAIL,operator FROM user WHERE ID=?
==> Parameters: 1(Long)
<== Columns: ID, NAME, AGE, EMAIL, OPERATOR
<== Row: 1, Jone, 18, test1@baomidou.com, test
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@255d9277]
2018-10-08 17:21:46.706 INFO 912 --- [ main] lusStudyAutoFillMetainfoApplicationTests : before user:User(id=1, name=Jone, age=18, email=test1@baomidou.com, operator=test)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7d484fcd] was not registered for synchronization because synchronization is not active
2018-10-08 17:21:46.722 INFO 912 --- [ main] c.r.m.handler.MyMetaObjectHandler : start update fill ...
JDBC Connection [HikariProxyConnection@142561311 wrapping conn0: url=jdbc:h2:mem:test user=ROOT] will not be managed by Spring
==> Preparing: UPDATE user SET NAME=?, AGE=?, EMAIL=?, operator=? WHERE ID=?
==> Parameters: Jone(String), 12(Integer), test1@baomidou.com(String), Tom(String), 1(Long)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7d484fcd]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@67c6f4d8] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@980326486 wrapping conn0: url=jdbc:h2:mem:test user=ROOT] will not be managed by Spring
==> Preparing: SELECT ID,NAME,AGE,EMAIL,operator FROM user WHERE ID=?
==> Parameters: 1(Long)
<== Columns: ID, NAME, AGE, EMAIL, OPERATOR
<== Row: 1, Jone, 12, test1@baomidou.com, Tom
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@67c6f4d8]
2018-10-08 17:21:46.733 INFO 912 --- [ main] lusStudyAutoFillMetainfoApplicationTests : query user:User(id=1, name=Jone, age=12, email=test1@baomidou.com, operator=Tom)
2018-10-08 17:21:46.740 INFO 912 --- [ Thread-2] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext@61bcd567: startup date [Mon Oct 08 17:21:40 CST 2018]; root of context hierarchy
2018-10-08 17:21:46.748 INFO 912 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-10-08 17:21:46.754 INFO 912 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.

重点关注

1
2
3
query user:User(id=1049228348251709442, name=Tom, age=1, email=tom@qq.com, operator=Jerry)
before user:User(id=1, name=Jone, age=18, email=test1@baomidou.com, operator=test)
query user:User(id=1, name=Jone, age=12, email=test1@baomidou.com, operator=Tom)
-------------- 本文结束  感谢您的阅读 --------------
0%