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

时间:2018-04-21 10:28:02

标签: java spring hibernate spring-mvc spring-boot

我目前有一个实体,如下所示:

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

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

我的帖子方法如下:

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

4 个答案:

答案 0 :(得分:3)

<强> JPA

没有任何方法可以直接注释时间戳字段,但您可以使用@PrePersist@PreUpdate注释,只需很少的努力即可获得相同的结果。

<强>休眠

Spring Data JPA

答案 1 :(得分:2)

您可以创建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();
    }
}

答案 2 :(得分:2)

在您的实体中扩展以下抽象类:

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

不要忘记使用@EnableJpaAuditing

启用JPA审核功能

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

答案 3 :(得分:0)

通过@dimitrisli和@buddha答案的混合,很干净

@Data
@MappedSuperclass
public abstract class BaseEntity {

    @Column(updatable = false)
    @CreationTimestamp
    private LocalDateTime createdAt;
    @UpdateTimestamp
    private LocalDateTime updatedAt;
}

现在您所有的实体都可以像这样扩展该类

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

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