6

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

JPA @EntityListeners , @PrePersist 

and

Spring @RepositoryEventHandler, @HandleBeforeSave

Thanks.

user1321466
  • 1,889
  • 2
  • 21
  • 29

2 Answers2

7

@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.

Klaus Groenbaek
  • 4,820
  • 2
  • 15
  • 30
  • I found this answer https://stackoverflow.com/a/31155291/1780517 and It seems that there is also one VERY BIG different, @HandleBeforeSave called on Controller POST method and not on repository save. – user1321466 Jun 16 '17 at 12:32
  • The example you reference uses Spring DATA *REST*, when you POST it will call the save method of the repository internally. – Klaus Groenbaek Jun 20 '17 at 11:18
2

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..

user1321466
  • 1,889
  • 2
  • 21
  • 29