Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a trigger Before / After save method of Spring-Data Repository

I've got a big number of entities. For every entity I've got an interface that extends CrudRepository. Every entity is saved using *Repository.save(entity) method.

And I want to implement a logger like that:

  • have a separate database for logs with two tables: log & logdata
  • log table:
    • created
    • username
  • logdata table:
    • log_id
    • fieldname
    • value (of string)
  • when save or delete method runs, MyRepositoryTrigger should write a log message with all fields changed with field names and field values.

But how to write smth like that?

like image 322
Mikhail Kopylov Avatar asked Oct 26 '14 17:10

Mikhail Kopylov


People also ask

What happens if the argument for Save () method of CrudRepository is null?

So if the field is null in the entity to save , it will overwrite its value to null in the existing row.

How are Spring data repositories implemented by Spring?

In the repository interfaces, we can add the methods like findByCustomerNameAndPhone() (assuming customerName and phone are fields in the domain object). Then, Spring provides the implementation by implementing the above repository interface methods at runtime (during the application run).

What does @repository do in Spring?

Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.

What is difference between JpaRepository and CrudRepository?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

For trigger functionality you'll have to look at your DB but most likely it won't guarantee exclusivity of your CrudRepository DB activity since it's set upon creation/deletion/update of table/column.

If instead you want to imitate trigger functionality meaning something to fire without you having to set it up every single time before/after your CrudRepository#save()/delete() functionality then you are better off using Spring AOP functionality

@After("execution(* my.CrudRepository.save(..))")
public void log(JoinPoint point) {
    log.info(point.getSignature().getName() + " was called..");
}

You can find extensive Spring AOP programming documentation in the Spring Docs

like image 83
dimitrisli Avatar answered Sep 26 '22 00:09

dimitrisli