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

更新日期自动填充

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

背景

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

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));}
http://www.xdnf.cn/news/2855.html

相关文章:

  • LeetCode 热题 100_最小路径和(92_64_中等_C++)(多维动态规划)
  • TypeScript之type
  • IEEE会议:第十届网络安全与信息工程国际会议(ICCSIE 2025)
  • 资产定位解决方案:蓝牙Beacon如何实现低成本高效追踪
  • 【Android】谈谈DexClassLoader
  • dx11 龙书学习 第四章 dx11 准备工作
  • Unity AI-使用Ollama本地大语言模型运行框架运行本地Deepseek等模型实现聊天对话(二)
  • 天梯——链表去重
  • 基于STM32、HAL库的ATSHA204A安全验证及加密芯片驱动程序设计
  • 深度学习大模型: AI 阅卷替代人工阅卷
  • Field访问对象int字段,对象访问int字段,通过openjdk17 C++源码看对象字段访问原理
  • J-Link RTT打印输出调试信息
  • 深入蜂窝物联网:第二章 深度解读 NB-IoT:协议栈、部署与典型应用
  • 两地三中心
  • MySQL数据库(14)—— 使用C操作MySQL
  • 【ACL系列论文写作指北03-相关工作怎么写】-展示视野与定位创新
  • leetcode283-移动零
  • 第二章 信息技术发展(2.2 新一代信息技术及应用)
  • Linux428 chmod 0xxx 1xxx 2xxx 4xxx;umask;chown 属主属组 软件包rpm
  • ECharts散点图-散点图20,附视频讲解与代码下载
  • php数据库连接
  • Docker安装的mysql限制ip访问
  • [三分钟]web自动化测试(三):selenium自动化测试常用函数(下)
  • 基于蓝牙Beacon人员导航方案
  • 【Linux】第十二章 安装和更新软件包
  • 第七章:Server/Client Communication
  • 增量抽取的场景下,周期快照表最新分区的数据是如何生成?
  • 安卓开发学习随记
  • OpenCV 图形API(69)图像与通道拼接函数------将一个 GMat 类型的对象转换为另一个具有不同深度GMat对象函数convertTo()
  • vue3使其另一台服务器上的x.html,实现x.html调用中的函数,并向其传递数据。