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

前端 未结 1 1772
忘了有多久
忘了有多久 2021-01-02 03:03

If my Entity has calculated fields should be update before saving to database (db insert or update) How can I hook a method call before Hibernate o

相关标签:
1条回答
  • 2021-01-02 03:57

    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

    0 讨论(0)
提交回复
热议问题