Spring Data REST - difference between @PrePersist and @HandleBeforeCreate?

£可爱£侵袭症+ 提交于 2020-01-02 03:17:07

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!