13

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()?

Paul Verest
  • 60,022
  • 51
  • 208
  • 332

1 Answers1

27

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

Koitoer
  • 18,778
  • 7
  • 63
  • 86
  • 1
    Great. The only case left, how would do that for all entities without adding`@EntityListeners` annotation. – Paul Verest Jun 22 '16 at 14:52
  • I think you need to define the listeners per entity as they will receive the object within the method, but also there is an orm.xml file in which you can define the listeners and audits. – Koitoer Jun 22 '16 at 15:24