Business logic before to save an entity in Spring JPA

Viewed 8136

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?

1 Answers
Related