我目前有一个实体如下:
@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");
}
在您的实体中扩展以下抽象类:
@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
结合@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
您可以创建一个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();
}
}