java 如何让 created_at 列像自动创建 ID 一样自动生成创建日期时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49954812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:29:48  来源:igfitidea点击:

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

javaspringhibernatespring-mvcspring-boot

提问by Brett Freeman

I currently have an Entity as below:

我目前有一个实体如下:

@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;

Upon creation of this object, the value of createdAt and updatedAt shows null in the database and was wondering how I can implement code so that createdAt and updateAt automatically gets inserted?

创建此对象后,createdAt 和 updatedAt 的值在数据库中显示为 null,我想知道如何实现代码以便自动插入 createdAt 和 updateAt?

My post method is as below:

我的post方法如下:

@PostMapping("/products")
public ProductResponse createProduct(@Validated @RequestBody ProductForm productForm) {
    Product product = productForm.asProduct();
    Product createdProduct = productRepository.save(product);
    return new ProductResponse(createdProduct, "Product created");
}

回答by dimitrisli

JPA

日本特许经营协会

There isn't anything as convenient as annotating the Timestamp field directly but you could use the @PrePersist, @PreUpdateannotations and with little effort achieve the same results.

没有什么比直接注释 Timestamp 字段更方便的了,但是您可以使用@PrePersist,@PreUpdate注释并且毫不费力地获得相同的结果。

Hibernate

休眠

Spring Data JPA

弹簧数据 JPA

回答by buddha

You can create a BaseEntity. Each entity extends the BaseEntity. In the Base entity ,it will set the time automatically

您可以创建一个 BaseEntity。每个实体都扩展了 BaseEntity。在 Base 实体中,它会自动设置时间

@Data
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity implements Serializable {

    @Id
    @Column(name = "Id")
    private String id;

    @Column(name = "deleted", columnDefinition = "Bit(1) default false")
    private boolean deleted = false;

    @Column(name = "DataChange_CreatedBy", nullable = false)
    private String dataChangeCreatedBy;

    @Column(name = "DataChange_CreatedTime", nullable = false)
    private Date dataChangeCreatedTime;

    @Column(name = "DataChange_LastModifiedBy")
    private String dataChangeLastModifiedBy;

    @Column(name = "DataChange_LastTime")
    private Date dataChangeLastModifiedTime;

    @PrePersist
    protected void prePersist() {
        if (this.dataChangeCreatedTime == null) dataChangeCreatedTime = new Date();
        if (this.dataChangeLastModifiedTime == null) dataChangeLastModifiedTime = new Date();
    }

    @PreUpdate
    protected void preUpdate() {
        this.dataChangeLastModifiedTime = new Date();
    }

    @PreRemove
    protected void preRemove() {
        this.dataChangeLastModifiedTime = new Date();
    }
}

回答by Sarvar Nishonboev

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

不要忘记使用启用 JPA 审计功能 @EnableJpaAuditing

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

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

回答by Francis Robitaille

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

结合@dimitrisli 和@buddha 的答案,一些非常干净的东西是

@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& @EqualsAndHashCodeannotationannotations from lombok as it generate getter/setter

请注意,您可能不需要来自lombok 的@Data@EqualsAndHashCodeannotation注释,因为它会生成 getter/setter