当前位置: 首页 > news >正文

更新日期自动填充

今天刷到一个自动插入更新时间的帖子,在这里自己实现一下,加深印象。

背景

现在有一个文章表,其结构如下:

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));}

相关文章:

  • ESG跨境电商怎么样?esg跨境电商有哪些功用?
  • 【动手学大模型开发】使用 LLM API:ChatGPT
  • 使用Curl进行本地MinIO的操作
  • 30天通过软考高项-第六天
  • MTKAndroid12-13-开机应用自启功能实现
  • Vue 对话框出现时,为什么滚动鼠标还是能滚动底层元素
  • Spring系列四:AOP切面编程第三部分
  • 软件工程(一):黑盒测试与白盒测试
  • 如何在WordPress网站中设置双重验证,提升安全性
  • 打火机检测数据集VOC+YOLO格式925张1类别
  • 案例篇:如何用tcpdump和Wireshark识别潜在威胁
  • Finish技术生态计划: FinishRpc
  • 无线采发仪多通道 在结构健康与地质灾害监测中的应用 VS-Box振弦、温度及多信号采发仪
  • 【Vue.js】Vue3父子组件数据通信案例(基础案例)
  • Vue组件开发进阶:从通信原理到DOM异步更新实战
  • 【北京】昌平区某附小v3700存储双控故障维修案例
  • leetcode刷题日记——两数相加
  • C++20 小语法
  • Dockerfile 编写根据需求阶段而出现
  • 【Redis】基础4:作为分布式锁
  • 法治日报调查直播间“杀熟”乱象:熟客越买越贵,举证难维权不易
  • 中国黄金协会:一季度我国黄金产量同比增1.49%,黄金消费量同比降5.96%
  • 王一博赛车故障退赛冲上热搜,工作室回应:下次再战
  • 视频丨伊朗港口爆炸事件灭火工作已完成80%
  • 经济日报金观平:统筹国内经济工作和国际经贸斗争
  • VR数字沉浸体验又添新节目,泰坦尼克号驶进文旅元宇宙