如果我的实体具有已计算字段,应在保存到数据库(db insert或update)之前进行更新,如何在Hibernate或Spring Data Repository之前挂接方法调用save()
insert
update
save()
我认为最好的选择是EntityListener使用@PrePersist和@PreUpdate注释,为实体侦听器创建配置,然后您将可以访问要保存的每个实例,每次尝试使用以下方法持久化或更新内容时都会调用此方法hibernate或spring数据存储库
EntityListener
@PrePersist
@PreUpdate
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 {
检查此链接以获取更多参考