使用關係型數據庫時,基本每張表都會包含created_time,modified_time,created_by,modified_by 這四個字段,一般情況下這四字個字段都有初始值,例如插入數據時前兩個字段爲當前時間,後面兩個字段一般是開發者或者工程名等,修改數據時modified_time也爲當前時間。因此可以使用mybatis plus 中的auto fill 功能爲這四個值設值。以下案例以postgresql爲基礎。
首先,pom文件必要的兩個依賴如下:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
其次,將這四個字段封裝成Base
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class Base {
@TableField(fill = FieldFill.INSERT_UPDATE)
private String createdBy;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime createdTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private String modifiedBy;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime modifiedTime;
}
然後,創建handler,這一步是實現自動填充的關鍵,且需要交給spring容器來管理,因此要加上@Component
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @author :channing
* @date :Created in 5/9/2020 4:58 PM
*/
@Slf4j
@Component
public class Af4pgMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start auto fill ....");
this.setFieldValByName("createdTime", LocalDateTime.now(), metaObject);
this.setFieldValByName("createdBy", "gbms", metaObject);
this.setFieldValByName("modifiedTime", LocalDateTime.now(), metaObject);
this.setFieldValByName("modifiedBy", "gbms", metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start auto update ....");
this.setFieldValByName("modifiedTime", LocalDateTime.now(), metaObject);
}
}
定義Mapper層
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.channing.af.entity.Goods;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface GoodsMapper extends BaseMapper<Goods> {
}
配置文件
spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/af4pg
username: postgres
password: postgres
platform: POSTGRESQL
mybatis-plus:
global-config:
db-config:
id-type: assign_id
capital-mode: true
logging:
level:
com.baomidou.samples.metainfo: debug
源碼:https://github.com/igdnss/AF4PG.git
本文參考聶老師的講解:https://gitee.com/baomidou/mybatis-plus-samples.git