search
HomeJavajavaTutorialPublic field automatic filling in Mybatis Plus

Public field automatic filling in Mybatis Plus

May 10, 2017 am 09:20 AM
bootmybatisspringautofill

This article mainly introduces the relevant information of SpringBoot Mybatis Plus public field automatic filling function. Friends who need it can refer to it

1. Application scenarios

Usually when building an object table, there will be two fields: last modification time and last modification person. For these fields that most tables have, these must be taken into consideration every time when adding or modifying. It's very troublesome to know whether several fields have been passed in. mybatisPlus has a great solution. That is the function of automatic filling of public fields. Generally, this function can be used for fields that meet the following conditions:

This field is found in most tables.

The value of this field is fixed, or the field value can be obtained dynamically in the background.

The two fields commonly used are last_update_time and last_update_name.

2. Configure MybatisPlus

Guide package: The only thing to note is that mybatisPlus is only supported in version 2.0.6Update Data public fields are automatically filled in. Previously, they could only be used when adding new data.

If you are a student who has configured MybatisPlus before, you only need to add the following steps:

Inherit IMetaObjectHandlerAbstract class, implement insertFill() new There are two methods: field settings that need to be filled when adding data and field settings that need to be filled when updateFill() updates data:

package io.z77z.util;
import java.util.Date;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import io.z77z.entity.SysUser;
/** mybatisplus自定义填充公共字段 ,即没有传的字段自动填充*/
@Component
public class MyMetaObjectHandler extends MetaObjectHandler {
  //新增填充
  @Override
  public void insertFill(MetaObject metaObject) {
    Object lastUpdateNameId = metaObject.getValue("lastUpdateNameId");
    Object lastUpdateTime = metaObject.getValue("lastUpdateTime");
    //获取当前登录用户
    SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal();
    if (null == lastUpdateNameId) {
      metaObject.setValue("lastUpdateNameId", user.getId());
    }
    if (null == lastUpdateTime) {
      metaObject.setValue("lastUpdateTime", new Date());
    }
  }
  //更新填充
  @Override
  public void updateFill(MetaObject metaObject) {
    insertFill(metaObject);
  }
}

Note: The parameters of the getValue() method are variables in the pojo class (Camel case naming method).

In the configuration file of mybatisplus, the bean of the public field generation class:

// MP 全局配置,更多内容进入类看注释
GlobalConfiguration globalConfig = new GlobalConfiguration();
//配置公共字段自动填写
globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());

is the setting to fill in the public field just written to the MP global configuration object.

Filled fields need to ignore validation, add the following annotation on the corresponding attribute of the table object pojo class:

/**
 * 最后修改人Id
 */
@TableField(value="last_update_id",validate=FieldStrategy.NOT_EMPTY)
private String lastUpdateNameId;
/**
 * 最后修改时间
 */
@TableField(value="last_update_time",validate=FieldStrategy.NOT_EMPTY)
private Date lastUpdateTime;

Reason: Because when the update and insert methods are called, It will verify whether the attribute you passed is empty to determine whether this attribute should be updated and inserted. This conflicts with the automatic filling of public fields, so this annotation is needed to identify that this attribute does not require verification. Otherwise, the filling will fail during insertion.

3. Writing test classes

//公共字段自动填充
//1.在mybatisplus的配置文件中公共字段生成类的bean
//2.实现IMetaObjectHandler类
//3.忽略对应字段的为空检测,在pojo类的属性上添加@TableField(value="last_update_name_id",validate=FieldStrategy.IGNORED)
@Test
public void publicTest(){
  SysUser user = new SysUser();
  user.setEmail("1093615728@qq.com");
  user.setNickname("z77z");
  user.setPswd("123123");
  user.setStatus("1");
  sysUserService.insert(user);
  sysUserService.selectById(user.getId());
  SysUser user1 = new SysUser();
  user1.setPswd("123");
  user1.setId(user.getId());
  sysUserService.updateById(user1);
  sysUserService.selectById(user.getId());
}

4. Test log

2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.insert- ==> Preparing: INSERT INTO sys_user (id, nickname, email, pswd, `status`,last_update_name_id , last_update_time ) VALUES ( ?, ?, ?, ?, ?,?, ? )
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.insert- ==> ; Parameters: 6634923de4a14b6ca3bac5fdf31563a8(String), z77z(String), 1093615728@qq.com(String), 123123(String), 1(String), 123(String), 2017-04-23 19:35:26.58(Time stamp)
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.insert- 2017/04/23-19:35:26 [ main] DEBUG io.z77z.dao.SysUserMapper.selectById- ==> createTime FROM sys_user WHERE id=?
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.selectById- ==> Parameters: 6634923de4a14b6ca3bac5fdf31563a8(String)
2017/ 04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.selectById- 2017/04/23-19:35:26 [main] DEBUG io. z77z.dao.SysUserMapper.updateById- ==> Preparing: UPDATE sys_user SET pswd=?, last_update_name_id=?, last_update_time=? WHERE id=?
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.updateById- ==> /04 /23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.updateById- 2017/04/23-19:35:26 [main] DEBUG io.z77z .dao.SysUserMapper.selectById- ==> Preparing: SELECT id,nickname,email,pswd,last_login_time AS lastLoginTime,`status`,last_update_name_id AS lastUpdateNameId,create_name_id AS createNameId,last_update_time AS lastUpdateTime,create_time AS createTime FROM sys_user WHERE id= ?
2017/04/23-19:35:26 [main] DEBUG io.z77z.dao.SysUserMapper.selectById- ==> Parameters: 6634923de4a14b6ca3bac5fdf31563a8(String)
2017/04/23-19: 35:26 [main] DEBUG io.z77z.dao.SysUserMapper.selectById-

##5. Summary

It was originally planned to use this method to process the creator and creation time. Finally, it was found that if these two fields are also ignored as empty, that is, validate=FieldStrategy.NOT_EMPTY is added when updating the data. The creator and creation time will be updated together. Otherwise, it will be updated to empty. So I think the public field autofill function of mybatisPlus is good, but it is not perfect when used for real needs.

【Related recommendations】

1. Free Java video tutorial

2. Comprehensive analysis of Java annotations

3. Alibaba Java Development Manual

The above is the detailed content of Public field automatic filling in Mybatis Plus. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool