Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differences between JPA @EntityListeners , @PrePersist and Spring @RepositoryEventHandler, @HandleBeforeSave

I did some research but was not able to find what is a differences between

JPA @EntityListeners , @PrePersist 

and

Spring @RepositoryEventHandler, @HandleBeforeSave

Thanks.

like image 319
user1321466 Avatar asked Jun 16 '17 09:06

user1321466


2 Answers

@HandleBeforeSave only works when an Entity is saved through a Spring Data repository. @PrePersist will be trigger if you use EntityManager::persist() and if you use JPARepository::save(), since it calls persist.

The nice thing with @RepositoryEventHandler+@HandleBeforeSaveis that your @HandleBeforeSave method is defined inside a spring bean, so you can interact with other spring beans. @EntityListeners and @PrePersist can only access the state of the current Entity when operating in a J2SE environment. In J2EE you can @Inject beans into a @EntityListeners because the JPA subsystem and CDI are both managed by the same Container.

like image 128
Klaus Groenbaek Avatar answered Oct 17 '22 17:10

Klaus Groenbaek


Actually after more searching I found this answer stackoverflow.com/a/31155291/1780517

It seems that there is also one VERY BIG different, @HandleBeforeSave called on Controller POST method and not on repository save. So @RepositoryEventHandler should be used only if you want handle events from controller (PUT, POST, GET with@HandleBeforeSave, @HandleBeforeCreate ..) and @EntityListeners should be used for repository method save,delete, update with @PreUpdate , @PreRemove and so on..

like image 32
user1321466 Avatar answered Oct 17 '22 17:10

user1321466