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

问题描述 投票:0回答:4

我目前有一个实体如下:

@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 和updateAt 的值在数据库中显示为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");
}
java spring hibernate spring-mvc spring-boot
4个回答
84
投票

JPA

没有什么比直接注释 Timestamp 字段更方便的了,但是您可以使用

@PrePersist
@PreUpdate
注释,并且不费吹灰之力就能达到相同的结果。

休眠

Spring Data JPA


33
投票

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

@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


26
投票

结合@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
@EqualsAndHashCode
注释,因为它会生成 getter/setter


18
投票

您可以创建一个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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.