You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现JPA实体中createdAt、updatedAt字段自动填充时间?

嘿,我来帮你搞定JPA实体类自动填充createdAt和updatedAt的问题!针对你的Product实体,有两种简单靠谱的实现方式,我给你详细拆解:

方法一:使用JPA生命周期回调注解(@PrePersist & @PreUpdate)

这种方式不需要额外配置,直接在实体类里添加回调方法就能实现,适合快速搞定单个实体的需求。

修改你的Product实体类,添加两个生命周期回调方法:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long productId;
    private String productImage;
    private String productTitle;
    private String productDescription;
    private Integer productPrice;
    private Date createdAt;
    private Date updatedAt;

    // 实体第一次持久化(插入数据库)前触发
    @PrePersist
    protected void onCreate() {
        Date now = new Date();
        createdAt = now;
        updatedAt = now; // 初始化时让更新时间和创建时间一致
    }

    // 实体更新前触发
    @PreUpdate
    protected void onUpdate() {
        updatedAt = new Date();
    }

    // 记得添加上所有字段的getter和setter方法
}

原理说明:

  • @PrePersist:会在实体首次被保存到数据库时自动调用,此时我们把createdAt和updatedAt都设置为当前时间。
  • @PreUpdate:会在实体执行更新操作前自动调用,此时只更新updatedAt字段即可。
方法二:使用Spring Data JPA Auditing功能

如果你的项目里有多个实体都需要创建/更新时间的自动填充,这种方式会更优雅、更统一,属于Spring Data JPA提供的审计能力。

步骤1:开启JPA审计功能

在你的Spring Boot主启动类或者配置类上添加@EnableJpaAuditing注解:

@SpringBootApplication
@EnableJpaAuditing
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

步骤2:改造Product实体类

使用Spring提供的@CreatedDate和@LastModifiedDate注解替代手动设置,同时添加@EntityListeners启用审计监听器:

@Entity
@EntityListeners(AuditingEntityListener.class) // 绑定审计监听器
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long productId;
    private String productImage;
    private String productTitle;
    private String productDescription;
    private Integer productPrice;

    @CreatedDate // 自动填充创建时间
    @Column(updatable = false) // 确保创建时间不会被后续更新操作修改
    private Date createdAt;

    @LastModifiedDate // 自动填充更新时间
    private Date updatedAt;

    // 添加上所有字段的getter和setter方法
}

额外推荐:使用Java 8+的LocalDateTime替代Date

Date是Java中过时的日期API,推荐使用LocalDateTime来替代,代码调整如下:

@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;

@LastModifiedDate
private LocalDateTime updatedAt;

Spring Data JPA的审计注解对LocalDateTime同样支持,而且它的线程安全性和可读性更好。


内容的提问来源于stack exchange,提问作者Brett Freeman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:39:19