Home Java javaTutorial Public field automatic filling in Mybatis Plus

Public field automatic filling in Mybatis Plus

May 10, 2017 am 09:20 AM
boot mybatis spring autofill

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);
  }
}
Copy after login

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());
Copy after login

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;
Copy after login

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());
}
Copy after login

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- <== Updates: 1
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- <==  Total: 1
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- <== Updates: 1
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- <== Total: 1

##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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Feb 23, 2024 pm 08:13 PM

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

Detailed explanation of MyBatis cache mechanism: understand the cache storage principle in one article Detailed explanation of MyBatis cache mechanism: understand the cache storage principle in one article Feb 23, 2024 pm 04:09 PM

Detailed explanation of MyBatis caching mechanism: One article to understand the principle of cache storage Introduction When using MyBatis for database access, caching is a very important mechanism, which can effectively reduce access to the database and improve system performance. This article will introduce the caching mechanism of MyBatis in detail, including cache classification, storage principles and specific code examples. 1. Cache classification MyBatis cache is mainly divided into two types: first-level cache and second-level cache. The first-level cache is a SqlSession-level cache. When

Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Feb 25, 2024 pm 12:30 PM

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

MyBatis Generator configuration parameter interpretation and best practices MyBatis Generator configuration parameter interpretation and best practices Feb 23, 2024 am 09:51 AM

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

Security First: Best Practices to Prevent SQL Injection in MyBatis Security First: Best Practices to Prevent SQL Injection in MyBatis Feb 22, 2024 pm 12:51 PM

As network technology continues to develop, database attacks are becoming more and more common. SQL injection is one of the common attack methods. Attackers enter malicious SQL statements into the input box to perform illegal operations, causing data leakage, tampering or even deletion. In order to prevent SQL injection attacks, developers must pay special attention when writing code, and when using an ORM framework such as MyBatis, they need to follow some best practices to ensure the security of the system. 1. Parameterized query Parameterized query is the anti-

In-depth understanding of MyBatis dynamic SQL tags: Trim tag function analysis In-depth understanding of MyBatis dynamic SQL tags: Trim tag function analysis Feb 21, 2024 pm 09:42 PM

MyBatis is a lightweight Java persistence layer framework that provides many convenient SQL statement splicing functions, among which dynamic SQL tags are one of its powerful features. In MyBatis, the Trim tag is a very commonly used tag, used to dynamically splice SQL statements. In this article, we will take a deep dive into the functionality of the Trim tag in MyBatis and provide some concrete code examples. 1. Introduction to Trim tag In MyBatis, the Trim tag is used to remove the generated S

See all articles