更新日期自动填充
今天刷到一个自动插入更新时间的帖子,在这里自己实现一下,加深印象。
背景
现在有一个文章表,其结构如下:
create table post
(id bigint auto_increment comment 'id' primary key,title varchar(512) null comment '标题',content text null comment '内容',tags varchar(1024) null comment '标签列表(json 数组)',thumbNum int default 0 not null comment '点赞数',favourNum int default 0 not null comment '收藏数',userId bigint not null comment '创建用户 id',createTime datetime default CURRENT_TIMESTAMP not null comment '创建时间',updateTime datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',isDelete tinyint default 0 not null comment '是否删除'
)comment '帖子' collate = utf8mb4_unicode_ci;create index idx_userIdon post (userId);
手动插入
@PostMapping("/add")
public ResponseEntity<Post> add(@RequestBody Post post) {// 获取当前时间if (post.getCreatetime() == null) {post.setCreatetime(new java.util.Date());}if (post.getUpdatetime() == null) {post.setUpdatetime(new java.util.Date());}return ResponseEntity.ok(this.postService.insert(post));
}
最原始方法为每次操纵数据库时都手动插入,但这样太繁琐。
自动插入
1. mybatis-plus自动填充
需要在application.yaml中进行配置mybatis-plus
1.1实体类配置
package com.fenghua.orderautofill.entity;import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;import java.util.Date;
import java.io.Serializable;/*** 帖子(Post)实体类** @author makejava* @since 2025-04-26 15:52:10*/
@Data
public class Post implements Serializable {private static final long serialVersionUID = 367930901201018200L;/*** id*/private Long id;/*** 标题*/private String title;/*** 内容*/private String content;/*** 标签列表(json 数组)*/private String tags;/*** 点赞数*/private Integer thumbnum;/*** 收藏数*/private Integer favournum;/*** 创建用户 id*/private Long userId;/*** 创建时间*/@TableField(value = "createTime", fill = FieldFill.INSERT)@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date createTime;/*** 更新时间*/@TableField(value = "updateTime", fill = FieldFill.INSERT_UPDATE)@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date updateTime;/*** 是否删除*/private Integer isDelete;}
1.2自动填充类
package com.fenghua.orderautofill.common;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.util.Date;/*** @ClassName DataAutoFill* @Description 自动填充日期* @Author Feng* @Date 2025/4/27**/
@Slf4j
@Component
public class DateAutoFill implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {log.info("新增时插入创建时间和更新时间");log.info(metaObject.toString());metaObject.setValue("createTime", new Date());metaObject.setValue("updateTime", new Date());metaObject.setValue("isDelete", 0);log.info("新增时插入创建时间和更新时间----结束喽");}@Overridepublic void updateFill(MetaObject metaObject) {log.info("更新时自动更新时间");metaObject.setValue("updateTime", new Date());}
}
1.3 mybatis-plus配置
在application.yml中配置mybatis-plus
spring:datasource:#数据库配置url: jdbc:mysql://localhost:3306/my_db?useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8username: ****password: ****driver-class-name: com.mysql.cj.jdbc.Drivermybatis-plus:configuration:map-underscore-to-camel-case: falselog-impl: org.apache.ibatis.logging.stdout.StdOutImplmapper-locations: classpath:/mapper/*.xmlglobal-config:db-config:logic-delete-field: isDelete # 全局逻辑删除的实体字段名logic-delete-value: 1 # 逻辑已删除值(默认为 1)logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)# springdoc-openapi项目配置
springdoc:swagger-ui:path: /swagger-ui.htmltags-sorter: alphaoperations-sorter: alphaapi-docs:path: /v3/api-docsgroup-configs:- group: 'default'paths-to-match: '/**'packages-to-scan: com.fenghua.orderautofill.controller
使用swagger进行测试
插入成功
2.AOP统一处理
2.1 自定义注解
package com.fenghua.orderautofill.annotation;import com.fenghua.orderautofill.enums.OperationType;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AutoFillDate {OperationType value();
}
2.2自定义枚举类
package com.fenghua.orderautofill.enums;public enum OperationType{INSERT,UPDATE
}
2.3切面实现
package com.fenghua.orderautofill.aop;import com.fenghua.orderautofill.annotation.AutoFillDate;
import com.fenghua.orderautofill.entity.Post;
import com.fenghua.orderautofill.enums.OperationType;
import org.springframework.stereotype.Component;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;import java.util.Date;/*** @ClassName DateInterceptor* @Description* @Author Feng* @Date 2025/4/27**/
@Aspect
@Component
public class DateInterceptor {@Around(value = "@annotation(autoFillDate)")public Object doInterceptor(ProceedingJoinPoint joinPoint, AutoFillDate autoFillDate) throws Throwable {// 获取方法参数Object[] args = joinPoint.getArgs();// 遍历参数,查找Post对象for (Object arg : args){if (arg instanceof Post){fillDate((Post) arg, autoFillDate.value());}}// 执行原方法return joinPoint.proceed();}private void fillDate(Post post, OperationType operationType){Date now = new Date();// 插入操作if (operationType == OperationType.INSERT) {post.setCreateTime(now);}post.setUpdateTime(now);post.setIsDelete(0);}
}
2.4使用自定义注解
@AutoFillDate(OperationType.INSERT)@PostMapping("/add")public ResponseEntity<Post> add(@RequestBody Post post) {return ResponseEntity.ok(this.postService.insert(post));}