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

I am using Spring Data Rest over JPA mappings.

JPA provides the @PrePersist annotation for methods that must be called before the en object is saved to the database.

Spring Data Rest provides the @HandleBeforeCreate annotation for the method that will be called when an entity creation event is detected.

It looks like me. When should I use one and when should I use the other?

+5
source share
1 answer
  • @HandleBeforeCreate is only called when a REST request is entered, but @PrePersist is called during the life cycles of objects. Thus, if your call path does not go through REST (for example, by calling the object manager directly or due to internal cascading JPA impl operations), you cannot catch the event with @HandleBeforeCreate.
  • Since @HandleBeforeCreate is called by Spring, it is easy to put it in a bean and use all the Spring functions for it. The entity listener lifecycle is controlled by JPA impl, so it usually takes a few tricks to connect to the Spring ecosystem.

For example, I use @HandleBeforeCreate, not @PrePersist for something like security checks. Since due to point 1 I only want to check the security for open rest operations and because of point 2, I can easily use @Secured or @PreAuth annotations with my methods for checking.

+5
source

Source: https://habr.com/ru/post/1233135/


All Articles