How can you make a created_at column generate the creation date-time automatically like an ID automatically gets created?

后端 未结 4 1085
小蘑菇
小蘑菇 2020-12-17 09:25

I currently have an Entity as below:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long productId;
          


        
4条回答
  •  臣服心动
    2020-12-17 09:44

    Extend the following abstract class in your entity:

    @MappedSuperclass
    @EntityListeners(AuditingEntityListener.class)
    public abstract class DateAudit implements Serializable {
        @CreatedDate
        @Column(name = "created_at", nullable = false, updatable = false)
        private Date createdAt;
    
        @LastModifiedDate
        @Column(name = "updated_at")
        private LocalDateTime updatedAt;
    }
    

    Don't forget to enable JPA Auditing feature using @EnableJpaAuditing

    Read this: https://docs.spring.io/spring-data/jpa/docs/1.7.0.DATAJPA-580-SNAPSHOT/reference/html/auditing.html

提交回复
热议问题