Search code examples
spring-data-jpaliquibaseauditingdatecreatedcreated-at

@CreatedDate annotation spring with Liquibase


I have these fields in my entity class:

import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate;

@CreatedDate
private Instant createdDate;

@LastModifiedDate
private Instant lastModifiedDate;

and I'm using Liquibase. When i run liqubase dates will work and sets up to fields.

But when I create a new entity via endpoint with postman it won't work. In the request I'm not writing dates it should automatically set dates and times. I'm not using any other configs or JpaAuditings or Listeners. Should I write some configs? I'm using this Annotation-based Auditing Metadata, did I misunderstand from docs?


Solution

  • I think you forgot the @EntityListeners(AuditingEntityListener.class) and @EnableJpaAuditing annotations.

    First you need to annotate @EnableJpaAuditing with @Configuration:

    @Configuration
    @EnableJpaAuditing
    public class AuditingConfig {
    }
    

    Then you should declare your entity class with `@EntityListeners(AuditingEntityListener.class)`:
    @Data
    @Entity
    @NoArgsConstructor
    @AllArgsConstructor
    @EntityListeners(AuditingEntityListener.class)
    public class Foo {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @Column(nullable = false)
        private String name;
    
        @CreatedDate
        @Column(updatable = false)
        private LocalDateTime createdAt;
    
        @LastModifiedDate
        private LocalDateTime updatedAt;
    }