Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

java - onSave() (for any Entity saved with Hibernate/Spring Data Repositories)

If my Entity has calculated fields should be updated before saving to database (db insert or update), How can I hook a method call before Hibernate or Spring Data Repository save()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think the best option for you are EntityListener using the @PrePersist and @PreUpdate annotations, create the configuration for your entity listener and you will get access to each instance that you want to save, this method is being called each time you are trying to persist or update something with hibernate or spring data repositories

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)
    }

}

You just need to add an annotation above your entity bean

@Entity
@Table(name = "", schema = "", catalog = "")
@EntityListeners(EntityToPersistListener.class)
public class EntityToPersist implements Serializable {

Check this link for further reference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...