Mybatis-plus学习
自动填充功能
-
实体类字段添加注解
package com.hw.mpstart.entity; import com.baomidou.mybatisplus.annotation.*; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDateTime; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; /** * <p> * * </p> * * @author 黄伟 * @since 2022-10-14 */ @KeySequence(value = "SEQ_JTEST") @Getter @Setter @TableName("J_TEST") @ApiModel(value = "JTest对象", description = "") public class JTest implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty("名称") private String name; @ApiModelProperty("密码") private String pw; @ApiModelProperty("备注") private String remark; @ApiModelProperty("主键") @TableId private String id; @ApiModelProperty("创建日期") @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; @ApiModelProperty("修改日期") @TableField(fill = FieldFill.INSERT_UPDATE,update = "sysdate")//自动填充注解 private LocalDateTime modifyTime; @ApiModelProperty("默认值") @TableField(fill = FieldFill.INSERT)//自动填充注解 private String defual; @ApiModelProperty("版本号") @TableField(fill = FieldFill.INSERT) @Version private Integer version; @ApiModelProperty("是否删除") @TableField(fill = FieldFill.INSERT) @TableLogic private BigDecimal isdelete; }
-
添加处理器类
package com.hw.mpstart.handler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.time.LocalDateTime; @Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject){ log.info("start insert fill ..."); this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "modifyTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject,"defual",String.class,"默认值"); this.strictInsertFill(metaObject,"version", Integer.class,1); this.strictInsertFill(metaObject,"isdelete",BigDecimal.class,new BigDecimal(0)); } @Override public void updateFill(MetaObject metaObject){ log.info("start update fill ..."); this.strictUpdateFill(metaObject,"modifyTime",LocalDateTime.class,LocalDateTime.now()); } }
-
使用乐观锁导致时间无法自动更新解决办法
@TableField(fill = FieldFill.INSERT_UPDATE,update = "sysdate")//实体类字段注解添加update = "sysdate",其中sysdate是对应数据库类型的系统日期获取方法