Springboot (51) – mybatis plus for automatic filling

Time:2022-6-20

preface

Already describedMyBatis-plusIf you are interested, please refer to the following articles
Springboot (40) – springboot integrates mybatis plus
Springboot (41) – mybatis plus common queries
Springboot (42) – some fields of a column of data in the mybatis plus query data table
Springboot (43) – some special queries for mybatis plus
Springboot (44) – mybatis plus custom SQL query
Springboot (45) – mybatis plus paging query
Springboot (46) – mybatis plus update data
Springboot (47) – mybatis plus delete data
Springboot (48) – mybatis plus basic configuration
Springboot (49) – mybatis plus general service
Springboot (50) – mybatis plus implements logical deletion
Today we are going to talk aboutMyBatis-plusAuto fill.

  1. Introduction to autofill
  2. Implementation of automatic filling
    2.1 adding fields to the data table
    2.2 add corresponding fields to table mapping entities
    2.3 compile data table operation mapper class
    2.4 implementation of automatic filling class
  3. Optimization of auto fill
  4. Auto fill test
  5. Auto fill considerations

I Introduction to autofill

staySpringbootDuring the development of, when we operate the database, we sometimes encounter this situation: addingCreation timeCreated byModification timeModified byAnd other relatively fixed data. withCreation timeFor example, the data to be filled in is usually the current time. Our general operation is to set a time for the data when filling in the data, and then add it to the database. The disadvantage of this treatment is that before adding a piece of data each time, a line of code like this should be set for the data to be added:setCreateTime(LocalDateTime.now()), this operation is very tedious, and it is easy to miss the time setting when adding data. Of course, we can also set the default value in the data table, but if it involvesCreated byIn case of change, the default value set in the database cannot meet the actual situation. If theCreated byData passsqlStatements and variables are still troublesome. So at this time, ourMyBatis-plusThe auto fill function can solve this headache.
Let’s explain it in detail.

II Implementation of automatic filling

2.1 adding fields to the data table

Below to auto fillCreation timeandModification timeFor example. First in the data sheettest_pro.demoTwo new fields are added to the table:createTimeandupdateTimetest_pro.demoThe table is shown below:

Springboot (51) - mybatis plus for automatic filling

image.png
2.2 add corresponding fields to table mapping entities

Here andtest_pro.demoEntity class of table mappingStudentThe codes are as follows: