Java:Mybatis-Plus自动填充功能配置和使用

在这里插入图片描述

Mybatis-Plus可以实现字段自动填充功能

文档

需求

我们需要自动填充的字段:

  • 插入数据时自动填充:create_time、update_time、deleted
  • 更新数据时自动填充:update_time

可以数据库设置默认值,也可以通过代码的方式进行自动填充

数据库设置默认值

数据库设置默认值

CREATE TABLE `tb_user` (
  `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `username` varchar(128) NOT NULL COMMENT '用户名',
  `phone` varchar(32) NOT NULL DEFAULT '' COMMENT '手机号',
  `sex` char(1) NOT NULL DEFAULT '' COMMENT '性别',

  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` tinyint NOT NULL DEFAULT '0' COMMENT '1、删除 0、未删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='用户表';

通过代码的方式进行自动填充

实体类

package com.example.demo.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDateTime;

@Data
@Accessors(chain = true)
@TableName("tb_user")
public class UserDO implements Serializable {
    
    

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 用户名
     */
    @TableField("username")
    private String username;

    /**
     * 手机号
     */
    @TableField("phone")
    private String phone;

    /**
     * 性别
     */
    @TableField("sex")
    private String sex;

    /**
     * 创建时间
     */
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;

    /**
     * 1、删除 0、未删除
     */
    @TableField(value = "deleted", fill = FieldFill.INSERT)
    private Integer deleted;
}

字段填充策略枚举类

public enum FieldFill {
    
    
    /**
     * 默认不处理
     */
    DEFAULT,
    /**
     * 插入时填充字段
     */
    INSERT,
    /**
     * 更新时填充字段
     */
    UPDATE,
    /**
     * 插入和更新时填充字段
     */
    INSERT_UPDATE
}

配置自动填充

  • 插入时自动填充 insertFill
  • 更新时自动填充 updateFill

设置方式一

// 如果属性不存在,会报错:
// There is no setter for property named 'createTime'
metaObject.setValue("createTime", LocalDateTime.now());

// 设置前需要判断
if (metaObject.hasSetter("createTime")) {
    
    
    metaObject.setValue("createTime", LocalDateTime.now());
}

完整代码

package com.example.demo.config;

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;

/**
 * 自动填充元数据
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    
    /**
     * 插入时自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
    
    
        
        if (metaObject.hasSetter("createTime")) {
    
    
            metaObject.setValue("createTime", LocalDateTime.now());
        }

        if (metaObject.hasSetter("updateTime")) {
    
    
            metaObject.setValue("updateTime", LocalDateTime.now());
        }

        if (metaObject.hasSetter("deleted")) {
    
    
            metaObject.setValue("deleted", 0);
        }
    }

    /**
     * 更新时自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
    
    
        if (metaObject.hasSetter("updateTime")) {
    
    
            metaObject.setValue("updateTime", LocalDateTime.now());
        }
    }
}

设置方式二

// 起始版本 3.3.3(推荐)
this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);

完整配置方式

package com.example.demo.config;

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;

/**
 * 自动填充元数据
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    
    /**
     * 插入时自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
    
    
        // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);

        this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);

        this.strictInsertFill(metaObject, "deleted", () -> 1, Integer.class);
    }

    /**
     * 更新时自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
    
    
        // 起始版本 3.3.3(推荐)
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    }
}

测试

package com.example.demo;

import com.example.demo.entity.UserDO;
import com.example.demo.mapper.UserMapper;
import org.assertj.core.util.Lists;
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;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SqlInjectorTest {
    
    

    @Autowired
    private UserMapper mapper;

    @Test
    public void insert() {
    
    
        UserDO user = new UserDO();
        user.setUsername("刘备");
        user.setSex("男");

        mapper.insert(user);
        // INSERT INTO tb_user ( username, sex, create_time, update_time, deleted ) VALUES ( ?, ?, ?, ?, ? )
        // 刘备(String), 男(String), 2023-06-02T13:50:22.769(LocalDateTime), 2023-06-02T13:50:22.769(LocalDateTime), 1(Integer)
    }

    @Test
    public void updateById() {
    
    
        UserDO user = new UserDO();
        user.setUsername("刘备");
        user.setSex("女");
        user.setId(1);

        mapper.updateById(user);
        // UPDATE tb_user SET username=?, sex=?, update_time=? WHERE id=?
        // 刘备(String), 女(String), 2023-06-02T13:51:17.591(LocalDateTime), 1(Integer)
    }
}

可以看到实现了文章开始的字段自动填充需求

依赖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.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</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-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.5.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

猜你喜欢

转载自blog.csdn.net/mouday/article/details/131005315