Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Business logic before to save an entity in Spring JPA

I'm using Spring Boot 1.5.4, Spring Data REST, Spring JPA, Hibernate and I'm developing a Angular client consuming REST API.

Spring Data REST helps a lot and I'm trying to follow best practice, so a repository is like:

@Transactional
@PreAuthorize("isAuthenticated()")
public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {
}

and automagically I've all my save(), delete(), findXX() methods. That's great.

Now I'm wondering how if I need custom business logic to do before the entity is saved. let's say I need to do some kind of complex validation (involving queries on the db), and other backstage activities (maybe saving related entities, updating related objects, ect). My goals are:

  1. Ensure every time the entity is saved (either from a REST call or a JPA call) my business logic is called before the object is saved
  2. Avoid to create a custom repository because a developer could call the standard repository breaking my rules
  3. Find a way to do this in a simple way in order to keep the app easy to mantain

The @RepositoryEventHandler is not enough for me because I want ensure my business logic is always verified even when the call to the method come from internal classes.

Could you suggest me the best approach to reach my goals?

like image 216
drenda Avatar asked Jul 12 '17 17:07

drenda


1 Answers

JPA has a bunch of entity listener.

@PrePersist Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.
@PreRemove  Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
@PostPersist    Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.
@PostRemove Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
@PreUpdate  Executed before the database UPDATE operation.
@PostUpdate Executed after the database UPDATE operation.
@PostLoad   Executed after an entity has been loaded into the current persistence context or an entity has been refreshed.
like image 160
Abhijit Sarkar Avatar answered Oct 23 '22 13:10

Abhijit Sarkar