MyBatis-Plus autofill

MyBatis-Plus autofill

1. Update operation

How to modify the field information of the record according to the idprimary ?

//更新操作
@Test
public void testUpdate(){
    
    
    User user = new User();
    //通过条件自动拼接动态sql
    user.setId(1495598121235881986L);
    user.setName("YCloud");
    user.setAge(18);

    //注意:updateById 的参数是一个对象
    //表示根据 id 修改数据信息
    int i = userMapper.updateById(user);
    //返回值i,表示改动记录的条数
    System.out.println(i);
}

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-7mBEfU1u-1645441432437) (C:\Users\17209\AppData\Roaming\Typora\typora-user-images\ image-20220221162706787.png)]

Note: All SQL is done automatically with dynamic parameter matching.

2. Autofill function

In scenarios such as user information or order management, there are often two fields create_timeand update_timeto record the time of data insertion and modification. These operations are done automatically and do not need to be updated manually.

Alibaba Development Manual: Almost all data tables need to be configured with two fields, gmt_create and gmt_modified, which are used to mark the time information of data insertion and update, and need to be automated.

Method 1: Database level (deprecated)

1. Add fields create_time, update_time to the table, and set the default value for the time field CURRENT_TIMESTAMP;

Note: Create_time does not need to check [Update according to the current timestamp], and update_time needs to check this item. At the same time, you need to set the default value of CURRENT_TIMESTAMP for the two fields. The database visualization tool I use here is Navicat.

2. Synchronize the modification of the data table fields with the entity class, and test the insertion method again;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    private String name;
    private Integer age;
    private String email;

    //注意:这里使用驼峰命名,将create_time与createTime映射起来
    private Date createTime;
    private Date updateTime;
}

3. Test the insert and update operations in the test class and observe the test results;

//测试插入操作
@Test
public void testInsert(){
    
    
    User user = new User();
    user.setName("D.Zhang");
    user.setAge(35);
    user.setEmail("[email protected]");
    int res = userMapper.insert(user);
    System.out.println(res);
    System.out.println(user);
}

//更新操作
@Test
public void testUpdate(){
    
    
    User user = new User();
    user.setId(1495683732378550273L);
    //修改插入数据的年龄和邮箱
    user.setAge(38);
    user.setEmail("[email protected]");
    int i = userMapper.updateById(user);
    System.out.println(i);
}

After the update operation is performed, it is observed that the create_timeand update_timefield values ​​of the data table are not the same.

Note: In actual work, developers are not allowed to modify the database at will, so this method is not recommended.


Method 2: Code level

Add annotations to the field attributes of the entity class. When the @TableFieldannotations are mapped to other fields, it fillmeans auto-filling, and MyBatis Plus automatically assigns values ​​to the fields for time-type data .

1. Add create_time and update_time fields to the table, and do not provide default values;

2. Add member variables createTime and updateTime to the entity class;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    private String name;
    private Integer age;
    private String email;

    //字段添加填充内容
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

3. Create an autofill processor;

package com.trainingl.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component  //一定不要忘记把处理器加到IOC容器中
public class DataHandler implements MetaObjectHandler {
    
    
    //插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
    
    
        // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);

    }
    //更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
    
    
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

4. Test the insertion operation;

@Test
public void testInsert(){
    
    
    User user = new User();
    user.setName("AnLiu");
    user.setAge(40);
    user.setEmail("[email protected]");
    int res = userMapper.insert(user);
    System.out.println(res);  //受影响的行数
    System.out.println(user);
}

The information printed from the console shows that when inserting a record, the current system time is automatically obtained and dynamically matched as a parameter to the SQL statement.

5. Test the update operation;

//更新操作
@Test
public void testUpdate(){
    
    
    User user = new User();
    //通过条件自动拼接动态sql
    user.setId(1495713047027740673L);
    user.setEmail("[email protected]");
    user.setAge(38);

    //注意:updateById 的 参数是一个对象
    int i = userMapper.updateById(user);
    System.out.println(i);
}

Modify the information of the record just inserted, and find that the update time of the record has also changed.

In actual development, it is more recommended to use this method to complete automatic filling.

Guess you like

Origin blog.csdn.net/qq_41775769/article/details/123053595