如果我的实体有计算字段,应该在保存到数据库之前更新(db insert
或 update
),
如何在 Hibernate 或 Spring Data Repository save()
之前 Hook 方法调用?
最佳答案
我认为对你来说最好的选择是 EntityListener
使用 @PrePersist
和 @PreUpdate
注释,为你的实体监听器创建配置您将可以访问要保存的每个实例,每次您尝试使用 hibernate 或 spring 数据存储库保存或更新某些内容时都会调用此方法
public class EntityToPersistListener{
@PrePersist
@PreUpdate
public void methodExecuteBeforeSave(final EntityToPersist reference) {
//Make any change to the entity such as calculation before the save process
reference.setAmount(xxxx)
}
}
你只需要在你的实体 bean 上面添加一个注解
@Entity
@Table(name = "", schema = "", catalog = "")
@EntityListeners(EntityToPersistListener.class)
public class EntityToPersist implements Serializable {
检查这个link进一步引用
关于java - onSave()(对于使用 Hibernate/Spring Data Repositories 保存的任何实体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37863178/