简体   繁体   English

如何实现触发器Spring-Data Repository的保存方法之前/之后

[英]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 . 对于每个实体,我都有一个扩展CrudRepository的接口。 Every entity is saved using *Repository.save(entity) method. 使用*Repository.save(entity)方法保存每个实体。

And I want to implement a logger like that: 我想要实现这样的记录器:

  • have a separate database for logs with two tables: log & logdata 有一个单独的数据库用于具有两个表的日志:log&logdata
  • log table: log表:
    • created 创建
    • username 用户名
  • logdata table: logdata表:
    • log_id 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. savedelete方法运行时,MyRepositoryTrigger应编写一条日志消息,其中所有字段都已更改为字段名称和字段值。

But how to write smth like that? 但是如何写那样的smth?

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. 对于触发器功能,您必须查看您的数据库,但很可能不会保证您的CrudRepository数据库活动的独占性,因为它是在创建/删除/更新表/列时设置的。

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 相反,如果您想模仿触发功能意味着需要点火,而不必在CrudRepository#save()/delete()功能之前/之后每次设置它,那么您最好使用Spring AOP功能

@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 您可以在Spring Docs中找到大量的Spring AOP编程文档

It looks like you are trying to implement audit log for the changes. 您似乎正在尝试为更改实施审核日志。 If you are using Spring Data JPA with Hibernate, I may recommend using Hibernate Envers that solves you everything. 如果您将Spring Data JPA与Hibernate一起使用,我可能会建议您使用Hibernate Envers来解决所有问题。 You add the maven dependency, then you add @Audited annotation on your entity (or on your interface), and envers will create an *_aud table for every entity you have audit on and add changelog automatically. 添加maven依赖项,然后在实体(或接口)上添加@Audited注释,envers将为您审计的每个实体创建一个* _aud表,并自动添加更改日志。

Storing user-id is a bit trickier, but you may find example here in the documentation for that as well . 存储用户ID有点棘手,但您也可以在文档中找到示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM