Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 545
JR Utily Avatar asked Oct 07 '15 10:10

JR Utily


People also ask

What is the use of spring boot starter data REST?

Spring Data REST builds on top of Spring Data repositories, analyzes your application's domain model and exposes hypermedia-driven HTTP resources for aggregates contained in the model.

What is used for exposing spring data repositories over REST using Spring data REST?

Spring Data REST can be used to expose HATEOAS RESTful resources around Spring Data repositories. Without writing a lot of code, we can expose RESTful API around Spring Data Repositories.

What is @RepositoryRestResource?

This is an interface that allows you to perform various operations with WebsiteUser objects. We also defined a custom query that will provide a list of users based on a given name. The @RepositoryRestResource annotation is optional and is used to customize the REST endpoint.

What is REST repository in spring boot?

This repository is an interface that lets you perform various operations involving Person objects. It gets these operations by extending the PagingAndSortingRepository interface that is defined in Spring Data Commons. At runtime, Spring Data REST automatically creates an implementation of this interface.


1 Answers

  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.

like image 196
tahagh Avatar answered Oct 30 '22 20:10

tahagh