Search code examples
javajpatriggersentitylisteners

Modify entity before flush


Is it possible to update some column before every flush to database? I have modifiedOn and modifiedBy columns and want to update them on every DB update, similar to DB trigger. Is it possible with JPA?


Solution

  • Disclaimer: The following works only with Hibernate / JPA.

    You can update the modifiedOn property like this with JPA:

    public class Entity {
    
         private Date modifiedOn;
    
         @PreUpdate 
         @PrePersist
         public void updateModified() {
             modifiedOn = new Date();
         }
    }
    

    As for the modifiedBy, it is a little bit trickier since the JPA spec discourages references to other entities in the lifecycle callback methods. Furthermore, you would need some knowledge of the current user, which probably belongs to the service layer.

    You could use an EntityListener like this (however, this still uses the callback methods)

    @Entity
    @EntityListeners({MyListener.class})
    public class MyEntity {
        Date modifiedOn;
        User modifiedBy;
        ...
    }
    

    An in the EntityListener:

    public class MyListener {
    
        CurrentUserProvider provider; // Implement this and make sure it is set
    
        @PreUpdate
        @PrePersist
        public void updateModifier(MyEntity entity) {
             entity.setModifiedOn(new Date());
             entity.setModifiedBy(provider.getCurrentUser());
        }
    }