使用Mybatis-Plus 自动填充功能

1. 实现监听处理类

创建一个自己的CreateAndUpdateEntityHandler:一个实现MP中MetaObjectHandler接口的类,并且重载insertFillupdateFill方法,并在这两个方法中编写插入和更新操作时填充的字段和逻辑。

package com.gangbb.core.config.mybatisplus;

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

import java.util.Date;

/**
 * @Author Gangbb
 * @Description MP 自动填充处理器
 * @Date 2021/7/22
 **/
@Component
public class CreateAndUpdateEntityHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            //根据属性名字设置要填充的值
            
            if (metaObject.hasGetter("createTime")) {
                if (metaObject.getValue("createTime") == null) {
                    this.setFieldValByName("createTime", new Date(), metaObject);
                }
            }

            // 正式启用式启用再添加这个
            /*if (metaObject.hasGetter("creator")) {
                if (metaObject.getValue("creator") == null) {
                    this.setFieldValByName("creator", SecurityUtils.getUsername(), metaObject);
                }
            }*/
        } catch (Exception e) {
            throw new ApiException("A0008-1", e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            // 正式启用式启用再添加这个
            /*if (metaObject.hasGetter("reviser")) {
                if (metaObject.getValue("reviser") == null) {
                    this.setFieldValByName("reviser", SecurityUtils.getUsername(), metaObject);
                }
            }*/

            if (metaObject.hasGetter("updateTime")) {
                if (metaObject.getValue("updateTime") == null) {
                    this.setFieldValByName("updateTime", new Date(), metaObject);
                }
            }
        } catch (Exception e) {
            throw new ApiException("A0008-2", e.getMessage());
        }
    }
}

注意如果这里不使用@Component注解声明,可以在Mybatis-Plus的配置文件MybatisPlusConfig中声明:

@Bean
public MetaObjectHandler metaObjectHandler() {
   return new CreateAndUpdateMetaObjectHandler();
}

2. 在相应字段上加@TableField注解

我这里是在实体类基类中的字段加上!

package com.gangbb.core.model.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;

import java.io.Serializable;
import java.util.Date;

/**
 * @author : Gangbb
 * @Description : 数据库实体类--Entity基类
 * @Date : 2021/3/7
 */
public class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    /** 主键id */
    private Long id;

    /** 创建者 */
    private String creator;

    /** 创建时间 */
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    /** 更新者 */
    private String reviser;

    /** 更新时间 */
    @TableField(fill = FieldFill.UPDATE)
    private Date updateTime;

    /** 是否删除 0-未删除  1-已删除 */
    @TableField(fill = FieldFill.INSERT)
    private Integer delFlag;

    /** 备注 */
    private String remark;

   	// get/set方法省略
}

3. 测试使用

TestMybatisPlus实体类已在

章节中给出。

package com.gangbb.test.controller.mp;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gangbb.common.model.ApiRestResponse;
import com.gangbb.test.enums.StatusEnum;
import com.gangbb.test.model.entity.TestMybatisPlus;
import com.gangbb.test.service.TestMPService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author Gangbb
 * @Description 测试MP自动填充功能
 * @Date 2021/7/22
 **/
@RestController
@RequestMapping("/test/mp")
public class TestMPHandlerController {

    @Autowired
    private TestMPService testMPService;

    @PostMapping("/handler1")
    public ApiRestResponse handler1(){
        TestMybatisPlus mybatisPlus = new TestMybatisPlus();
        mybatisPlus.setName("测试MP自动填充功能 插入1");
        mybatisPlus.setSex(1);
        mybatisPlus.setAge(333);
        String a = "启用";
        mybatisPlus.setStatus(StatusEnum.getEnum(a));
        testMPService.save(mybatisPlus);
        return ApiRestResponse.success();
    }


    @PostMapping("/handler2")
    public ApiRestResponse handler2(){
        UpdateWrapper<TestMybatisPlus> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("age",333).set("status", 3);
        testMPService.update(new TestMybatisPlus(), updateWrapper);


        TestMybatisPlus testMybatisPlus = new TestMybatisPlus();
        testMybatisPlus.setId(1417774262396010498L);
        testMybatisPlus.setName("修改后的名字");
        testMPService.update(testMybatisPlus);

        return ApiRestResponse.success();
    }

    /**
     * @Author Gangbb
     * @Description 先增加,再修改
     * @Date 2021/7/22
     **/
    @PostMapping("/handler3")
    public ApiRestResponse handler3(){
        TestMybatisPlus mybatisPlus = new TestMybatisPlus();
        mybatisPlus.setName("测试MP自动填充功能 插入1");
        mybatisPlus.setSex(1);
        mybatisPlus.setAge(333);
        String a = "启用";
        mybatisPlus.setStatus(StatusEnum.getEnum(a));
        testMPService.save(mybatisPlus);

        mybatisPlus.setSex(2);
        testMPService.update(mybatisPlus);

        return ApiRestResponse.success();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值