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

后端 未结 4 1086
小蘑菇
小蘑菇 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:38

    With the mix of @dimitrisli and @buddha answers, something pretty clean is

    @Data
    @MappedSuperclass
    public abstract class BaseEntity {
    
        @Column(updatable = false)
        @CreationTimestamp
        private LocalDateTime createdAt;
        @UpdateTimestamp
        private LocalDateTime updatedAt;
    }
    

    And now you all your entity can extend that class like so

    @Data
    @Entity
    @EqualsAndHashCode(callSuper = true)
    public class User extends BaseEntity {
    
        @Id
        @GeneratedValue
        public UUID id;
        public String userName;
        public String email;
        public String firstName;
        public String lastName;
    }
    

    Note that you might not need @Data & @EqualsAndHashCodeannotation annotations from lombok as it generate getter/setter

提交回复
热议问题