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

@CreationTimestamp与@UpdateTimestamp搭配LocalDate无效,字段值为null

问题:JPA @CreationTimestamp/@UpdateTimestamp字段插入时为null的解决

问题描述

实体类中使用Hibernate的@CreationTimestamp和@UpdateTimestamp注解自动填充时间字段,但插入数据库时dateAdded和lastEdited始终为null:

@CreationTimestamp
@Column(updatable = false)
private LocalDate dateAdded;
@JsonProperty("last_edited")
@UpdateTimestamp
@Column(updatable = false)
private LocalDate lastEdited;

环境:Java 18 + spring-boot-starter-jpa,目前已改用JDBC Template手动设置时间字段。

核心问题与修复方案

1. 注解冲突(关键问题)

lastEdited字段同时添加了@UpdateTimestamp和@Column(updatable = false),后者会禁止该字段被任何更新操作覆盖,直接导致@UpdateTimestamp无法生效。必须移除lastEdited的@Column(updatable = false)注解。

2. 字段类型适配问题

@CreationTimestamp和@UpdateTimestamp对LocalDateTime的支持比LocalDate更稳定,若数据库字段允许存储时间(而非仅日期),建议将实体类字段类型改为LocalDateTime:

@CreationTimestamp
@Column(updatable = false)
private LocalDateTime dateAdded;

@JsonProperty("last_edited")
@UpdateTimestamp
private LocalDateTime lastEdited;

若坚持使用LocalDate,需确保数据库字段为DATE类型,且在配置中指定Hibernate的时区:

spring.jpa.properties.hibernate.jdbc.time_zone=Asia/Shanghai # 替换为你的时区

3. 必须使用JPA持久化方法

如果直接用JDBC Template执行原生SQL,Hibernate的注解逻辑不会触发,因为JDBC Template绕过了JPA的实体管理流程。要让注解生效,需通过JpaRepository的save()方法操作实体:

// 定义Repository接口
public interface RecipeRepository extends JpaRepository<Recipe, Long> {}

// 服务层调用
@Service
public class RecipeService {
    private final RecipeRepository recipeRepo;

    public RecipeService(RecipeRepository recipeRepo) {
        this.recipeRepo = recipeRepo;
    }

    public Recipe save(Recipe recipe) {
        return recipeRepo.save(recipe); // 自动填充时间字段
    }
}

4. 配置与扫描检查

  • 确认application.properties中Hibernate配置正确:
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true # 可选,用于调试SQL语句
    
  • 确保实体类所在包被Spring Boot扫描,若不在启动类同包或子包,需添加@EntityScan注解到启动类:
    @SpringBootApplication
    @EntityScan("com.your.project.entity") // 替换为你的实体类包路径
    public class YourApplication {
        public static void main(String[] args) {
            SpringApplication.run(YourApplication.class, args);
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:36:16