问题
I use Spring Data Rest
over JPA
mappings.
JPA provides @PrePersist
annotation for methods to be called before the persistence of en entity in the DB.
Spring Data Rest provides @HandleBeforeCreate
annotation for method to be called when catching an entity creation event.
This seems rather equivalent to me. When should I use one and when should I use the other ?
回答1:
- @HandleBeforeCreate is only called when a REST request comes in but @PrePersist is called during the entities lifecycles. So, if your call path is not through the REST (for instance by calling the entity manager directly or due to the internal cascading operations of JPA impl) you can't catch the event with @HandleBeforeCreate.
- Since @HandleBeforeCreate is called by Spring, it is easy to place it into a bean and enjoy all Spring features for it. The entity listener's lifecycle is managed by JPA impl so it usually needs some tricks to be wired to Spring ecosystem.
For instance, I use @HandleBeforeCreate rather than @PrePersist for something like security checks. Since due to item 1, I only want to check the security for exposed rest operations and due to item 2, I can easily use @Secured or @PreAuth annotations with my methods to do the check.
来源:https://stackoverflow.com/questions/32989537/spring-data-rest-difference-between-prepersist-and-handlebeforecreate