Auditing with JPA, Hibernate, and Spring Data JPA – 用JPA、Hibernate和Spring Data JPA进行审计

最后修改: 2016年 1月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In the context of ORM, database auditing means tracking and logging events related to persistent entities, or simply entity versioning. Inspired by SQL triggers, the events are insert, update, and delete operations on entities. The benefits of database auditing are analogous to those provided by source version control.

在ORM的背景下,数据库审计意味着跟踪和记录与持久化实体有关的事件,或者简单地说,实体的版本。受SQL触发器的启发,这些事件是对实体的插入、更新和删除操作。数据库审计的好处类似于源代码版本控制所提供的好处。

In this tutorial, we’ll demonstrate three approaches to introducing auditing into an application. First, we’ll implement it using standard JPA. Next, we’ll look at two JPA extensions that provide their own auditing functionality, one provided by Hibernate, another by Spring Data.

在本教程中,我们将展示三种在应用程序中引入审计的方法。首先,我们将使用标准JPA来实现它。接下来,我们将看看两个JPA扩展,它们提供自己的审计功能,一个由Hibernate提供,另一个由Spring Data提供。

Here are the sample related entities, Bar and Foo, that we’ll use in this example:

下面是我们将在这个例子中使用的相关实体样本,BarFoo,

Screenshot_4

2. Auditing With JPA

2.用JPA进行审计

JPA doesn’t explicitly contain an auditing API, but we can achieve this functionality by using entity lifecycle events.

JPA并没有明确包含审计API,但我们可以通过使用实体生命周期事件来实现这一功能。

2.1. @PrePersist, @PreUpdate and @PreRemove

2.1.@PrePersist, @PreUpdate@PreRemove

In the JPA Entity class, we can specify a method as a callback, which we can invoke during a particular entity lifecycle event. As we’re interested in callbacks executed before the corresponding DML operations, the @PrePersist, @PreUpdate and @PreRemove callback annotations are available for our purposes:

在JPA的Entity类中,我们可以指定一个方法作为回调,我们可以在一个特定的实体生命周期事件中调用这个方法。由于我们对在相应的DML操作之前执行的回调感兴趣,@PrePersist, @PreUpdate@PreRemove 回调注解可以满足我们的目的。

@Entity
public class Bar {
      
    @PrePersist
    public void onPrePersist() { ... }
      
    @PreUpdate
    public void onPreUpdate() { ... }
      
    @PreRemove
    public void onPreRemove() { ... }
      
}

Internal callback methods should always return void, and take no arguments. They can have any name and any access level, but shouldn’t be static.

内部回调方法应该总是返回void,并且不接受任何参数。它们可以有任何名称和任何访问级别,但不应该是static

Be aware that the @Version annotation in JPA isn’t strictly related to our topic; it has to do with optimistic locking more than with audit data.

请注意,JPA中的@Version注解与我们的主题并不严格相关;它与乐观的锁定有关,而不是与审计数据有关。

2.2. Implementing the Callback Methods

2.2.实现回调方法

There’s a significant restriction with this approach though. As stated in JPA 2 specification (JSR 317):

不过这种方法有一个重要的限制。正如JPA 2规范(JSR 317)中所说:

In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context. A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked.

一般来说,可移植应用程序的生命周期方法不应该调用EntityManagerQuery操作、访问其它实体实例或修改同一持久化上下文中的关系。生命周期回调方法可以修改它所调用的实体的非关系状态。

In the absence of an auditing framework, we must maintain the database schema and domain model manually. For our simple use case, let’s add two new properties to the entity, as we can manage only the “non-relationship state of the entity.” An operation property will store the name of an operation performed, and a timestamp property is for the timestamp of the operation:

在没有审计框架的情况下,我们必须手动维护数据库模式和领域模型。对于我们的简单用例,让我们为实体添加两个新的属性,因为我们可以只管理 “实体的非关系状态”。一个operation属性将存储所执行的操作的名称,而一个timestamp属性是用于操作的时间戳。

@Entity
public class Bar {
     
    //...
     
    @Column(name = "operation")
    private String operation;
     
    @Column(name = "timestamp")
    private long timestamp;
     
    //...
     
    // standard setters and getters for the new properties
     
    //...
     
    @PrePersist
    public void onPrePersist() {
        audit("INSERT");
    }
     
    @PreUpdate
    public void onPreUpdate() {
        audit("UPDATE");
    }
     
    @PreRemove
    public void onPreRemove() {
        audit("DELETE");
    }
     
    private void audit(String operation) {
        setOperation(operation);
        setTimestamp((new Date()).getTime());
    }
     
}

If we need to add such auditing to multiple classes, we can use @EntityListeners to centralize the code:

如果我们需要在多个类中添加这种审计,我们可以使用@EntityListeners来集中代码。

@EntityListeners(AuditListener.class)
@Entity
public class Bar { ... }
public class AuditListener {
    
    @PrePersist
    @PreUpdate
    @PreRemove
    private void beforeAnyOperation(Object object) { ... }
    
}

3. Hibernate Envers

3.休眠的环境

With Hibernate, we can make use of Interceptors and EventListeners, as well as database triggers, to accomplish auditing. But the ORM framework offers Envers, a module implementing auditing and versioning of persistent classes.

通过Hibernate,我们可以利用InterceptorsEventListeners,以及数据库触发器,来完成审计工作。但是ORM框架提供了Envers,一个实现审计和持久化类的版本管理的模块。

3.1. Get Started With Envers

3.1.开始使用Envers

To set up Envers, we need to add the hibernate-envers JAR into our classpath:

为了设置Envers,我们需要将hibernate-envers JAR加入我们的classpath。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-envers</artifactId>
    <version>${hibernate.version}</version>
</dependency>

Then we add the @Audited annotation, either on an @Entity (to audit the whole entity) or on specific @Columns (if we need to audit specific properties only):

然后我们添加@Audited注解,可以在@Entity上(审计整个实体),也可以在特定的@Columns上(如果我们只需要审计特定属性)。

@Entity
@Audited
public class Bar { ... }

Note that Bar has a one-to-many relationship with Foo. In this case, we either need to audit Foo as well by adding @Audited on Foo, or set @NotAudited on the relationship’s property in Bar:

请注意,BarFoo有一对多的关系。在这种情况下,我们需要在Foo上添加@Audited来审计Foo,或者在Bar的关系属性上设置@NotAudited

@OneToMany(mappedBy = "bar")
@NotAudited
private Set<Foo> fooSet;

3.2. Creating Audit Log Tables

3.2.创建审计日志表

There are several ways to create audit tables:

有几种方法来创建审计表。

  • set hibernate.hbm2ddl.auto to create, create-drop, or update, so Envers can create them automatically
  • use org.hibernate.tool.EnversSchemaGenerator to export the complete database schema programmatically
  • set up an Ant task to generate appropriate DDL statements
  • use a Maven plugin for generating a database schema from our mappings (such as Juplo) to export Envers schema (works with Hibernate 4 and higher)

We’ll go the first route, as it’s the most straightforward, but be aware that using hibernate.hbm2ddl.auto isn’t safe in production.

我们将采用第一条路线,因为这是最直接的,但要注意,使用hibernate.hbm2ddl.auto在生产中并不安全。

In our case, the bar_AUD and foo_AUD (if we’ve set Foo as @Audited as well) tables should be generated automatically. The audit tables copy all audited fields from the entity’s table with two fields, REVTYPE (values are: “0” for adding, “1” for updating, and “2” for removing an entity) and REV.

在我们的例子中,bar_AUDfoo_AUD(如果我们把Foo也设置为@Audited)表应该被自动生成。审计表从实体的表中复制所有的审计字段,有两个字段,REVTYPE(值是。”0 “表示添加,”1 “表示更新,”2 “表示删除一个实体)和REV

Besides these, an extra table named REVINFO will be generated by default. It includes two important fields, REV and REVTSTMP, and records the timestamp of every revision. As we can guess, bar_AUD.REV and foo_AUD.REV are actually foreign keys to REVINFO.REV.

除了这些,默认情况下还会生成一个名为REVINFO的额外表。它包括两个重要的字段,REVREVTSTMP,并记录每个修订的时间戳。我们可以猜到,bar_AUD.REVfoo_AUD.REV实际上是REVINFO.REV>的外键。

3.3. Configuring Envers

3.3.配置Envers

We can configure Envers properties just like any other Hibernate property.

我们可以像其他Hibernate属性一样配置Envers属性。

For example, let’s change the audit table suffix (which defaults to “_AUD“) to “_AUDIT_LOG.” Here’s how we set the value of the corresponding property org.hibernate.envers.audit_table_suffix:

例如,让我们把审计表的后缀(默认为”_AUD“)改为”_AUDIT_LOG.“下面是我们如何设置相应属性org.hibernate.envers.audit_table_suffix的值。

Properties hibernateProperties = new Properties(); 
hibernateProperties.setProperty(
  "org.hibernate.envers.audit_table_suffix", "_AUDIT_LOG"); 
sessionFactory.setHibernateProperties(hibernateProperties);

A full listing of available properties can be found in the Envers documentation.

可用属性的完整列表可以在Envers文档中找到

3.4. Accessing Entity History

3.4.访问实体历史

We can query for historic data in a way similar to querying data via the Hibernate Criteria API.  We can access the audit history of an entity using the AuditReader interface, which we can obtain with an open EntityManager or Session via the AuditReaderFactory:

我们可以通过类似于通过Hibernate Criteria API查询数据的方式来查询历史数据。 我们可以使用AuditReader接口访问实体的审计历史,我们可以通过AuditReaderFactory获得开放的EntityManagerSession

AuditReader reader = AuditReaderFactory.get(session);

Envers provides AuditQueryCreator (returned by AuditReader.createQuery()) in order to create audit-specific queries. The following line will return all Bar instances modified at revision #2 (where bar_AUDIT_LOG.REV = 2):

Envers提供了AuditQueryCreator(由AuditReader.createQuery()返回),以便创建审计专用查询。下面一行将返回所有在修订版#2(其中bar_AUDIT_LOG.REV = 2)修改的Bar实例。

AuditQuery query = reader.createQuery()
  .forEntitiesAtRevision(Bar.class, 2)

Here’s how we can query for Bar‘s revisions. It’ll result in getting a list of all audited Bar instances in all their states:

下面是我们如何查询Bar的修订情况。这将导致得到一个所有被审计的Bar实例的列表,以及它们的所有状态。

AuditQuery query = reader.createQuery()
  .forRevisionsOfEntity(Bar.class, true, true);

If the second parameter is false, the result is joined with the REVINFO table. Otherwise, only entity instances are returned. The last parameter specifies whether to return deleted Bar instances.

如果第二个参数是false,结果将与REVINFO表连接。否则,只返回实体实例。最后一个参数指定是否返回已删除的Bar实例。

Then we can specify constraints using the AuditEntity factory class:

然后我们可以使用AuditEntity工厂类指定约束。

query.addOrder(AuditEntity.revisionNumber().desc());

4. Spring Data JPA

4.Spring Data JPA

Spring Data JPA is a framework that extends JPA by adding an extra layer of abstraction on the top of the JPA provider. This layer supports creating JPA repositories by extending Spring JPA repository interfaces.

Spring Data JPA是一个框架,它通过在JPA提供者之上增加一个额外的抽象层来扩展JPA。这一层支持通过扩展Spring JPA的存储库接口来创建JPA存储库。

For our purposes, we can extend CrudRepository<T, ID extends Serializable>, the interface for generic CRUD operations. As soon as we’ve created and injected our repository to another component, Spring Data will provide the implementation automatically, and we’re ready to add auditing functionality.

为了我们的目的,我们可以扩展CrudRepository<T,ID扩展Serializable>,该接口用于通用CRUD操作。一旦我们创建并将我们的存储库注入到另一个组件中,Spring Data就会自动提供实现,我们就可以添加审计功能了。

4.1. Enabling JPA Auditing

4.1.启用JPA审计

To start, we want to enable auditing via annotation configuration. In order to do that, we add @EnableJpaAuditing on our @Configuration class:

首先,我们要通过注解配置来启用审计。为了做到这一点,我们在@EnableJpaAuditing类上添加@Configuration

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories
@EnableJpaAuditing
public class PersistenceConfig { ... }

4.2. Adding Spring’s Entity Callback Listener

4.2.添加Spring的实体回调监听器

As we already know, JPA provides the @EntityListeners annotation to specify callback listener classes. Spring Data provides its own JPA entity listener class, AuditingEntityListener. So let’s specify the listener for the Bar entity:

我们已经知道,JPA提供了@EntityListeners注解来指定回调监听器类。Spring Data提供了自己的JPA实体监听器类,AuditingEntityListener。因此,让我们为Bar实体指定监听器。

@Entity
@EntityListeners(AuditingEntityListener.class)
public class Bar { ... }

Now we can capture auditing information by the listener upon persisting and updating the Bar entity.

现在我们可以在持久化和更新Bar实体时由监听器捕获审计信息。

4.3. Tracking Created and Last Modified Dates

4.3.追踪创建和最后修改的日期

Next, we’ll add two new properties for storing the created and last modified dates to our Bar entity. The properties are annotated by the @CreatedDate and @LastModifiedDate annotations accordingly, and their values are set automatically:

接下来,我们将为我们的Bar实体添加两个新的属性来存储创建和最后修改的日期。这些属性被@CreatedDate@LastModifiedDate注释相应地注解,它们的值被自动设置。

@Entity
@EntityListeners(AuditingEntityListener.class)
public class Bar {
    
    //...
    
    @Column(name = "created_date", nullable = false, updatable = false)
    @CreatedDate
    private long createdDate;

    @Column(name = "modified_date")
    @LastModifiedDate
    private long modifiedDate;
    
    //...
    
}

Generally, we move the properties to a base class (annotated by @MappedSuperClass), which all of our audited entities would extend. In our example, we add them directly to Bar for the sake of simplicity.

一般来说,我们把这些属性移到一个基类(由@MappedSuperClass注解),我们所有的被审计实体都将扩展这个基类。在我们的例子中,为了简单起见,我们将它们直接添加到Bar中。

4.4. Auditing the Author of Changes With Spring Security

4.4.用Spring Security审计更改的作者

If our app uses Spring Security, we can track when changes are made and who made them:

如果我们的应用程序使用Spring Security,我们就可以跟踪什么时候进行了修改以及谁做了修改。

@Entity
@EntityListeners(AuditingEntityListener.class)
public class Bar {
    
    //...
    
    @Column(name = "created_by")
    @CreatedBy
    private String createdBy;

    @Column(name = "modified_by")
    @LastModifiedBy
    private String modifiedBy;
    
    //...
    
}

The columns annotated with @CreatedBy and @LastModifiedBy are populated with the name of the principal that created or last modified the entity. The information comes from SecurityContext‘s Authentication instance. If we want to customize values that are set to the annotated fields, we can implement the AuditorAware<T> interface:

带有@CreatedBy@LastModifiedBy注释的列被填充为创建或最后修改该实体的委托人的名字。这些信息来自SecurityContextAuthentication实例。如果我们想自定义设置到注释字段的值,我们可以实现AuditorAware<T>/em>接口。

public class AuditorAwareImpl implements AuditorAware<String> {
 
    @Override
    public String getCurrentAuditor() {
        // your custom logic
    }

}

In order to configure the app to use AuditorAwareImpl to look up the current principal, we declare a bean of AuditorAware type, initialized with an instance of AuditorAwareImpl, and specify the bean’s name as the auditorAwareRef parameter’s value in @EnableJpaAuditing:

为了配置应用程序使用AuditorAwareImpl来查询当前的委托人,我们声明了一个AuditorAware类型的bean,用AuditorAwareImpl的实例进行初始化,并在@EnableJpaAuditing中指定该bean的名字作为auditorAwareRef参数的值:

@EnableJpaAuditing(auditorAwareRef="auditorProvider")
public class PersistenceConfig {
    
    //...
    
    @Bean
    AuditorAware<String> auditorProvider() {
        return new AuditorAwareImpl();
    }
    
    //...
    
}

5. Conclusion

5.结论

In this article, we considered three approaches to implementing auditing functionality:

在这篇文章中,我们考虑了三种实现审计功能的方法。

  • The pure JPA approach is the most basic and consists of using lifecycle callbacks. However, we’re only allowed to modify the non-relationship state of an entity. This makes the @PreRemove callback useless for our purposes, as any settings we made in the method will be deleted along with the entity.
  • Envers is a mature auditing module provided by Hibernate. It’s highly configurable and lacks the flaws of the pure JPA implementation. Thus, it allows us to audit the delete operation, as it logs into tables other than the entity’s table.
  • The Spring Data JPA approach abstracts working with JPA callbacks and provides handy annotations for auditing properties. It’s also ready for integration with Spring Security. The disadvantage is that it inherits the same flaws of the JPA approach, so the delete operation can’t be audited.

The examples for this article are available in a GitHub repository.

本文的例子可在GitHub 仓库中找到。