Auditing with JPA, Hibernate, and Spring Data JPA

今天在查询Auditing 写法的时候,发现国外一个网站讲的还不错,而且相对比较新.转过来记录下.

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 allows for support for creating JPA repositories by extending Spring JPA repository interfaces. For our purposes, you can extend CrudRepository<T, ID extends Serializable>, the interface for generic CRUD operations. As soon as you’ve created and injected your repository to another component, Spring Data will provide the implementation automatically and you’re ready to add auditing functionality.

4.1. Enabling JPA Auditing

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

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

4.2. Adding Spring’s Entity Callback Listener

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 Barentity:

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

Now auditing information will be captured by the listener on persisting and updating the Bar entity.

4.3. Tracking Created and Last Modified Dates

Next we will 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:

@Entity
@EntityListeners(AuditingEntityListener.class)
public class Bar {
    
    ...
    
    @Column(name = "created_date")
    @CreatedDate
    private long createdDate;
    @Column(name = "modified_date")
    @LastModifiedDate
    private long modifiedDate;
    
    ...
    
}

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

4.4. Auditing the Author of Changes with Spring Security

If your app uses Spring Security, you can not only track when changes were made but also who made them:

@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 is pulled from SecurityContext‘s Authentication instance. If you want to customize values that are set to the annotated fields, you can implement AuditorAware<T>interface:

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

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

@EnableJpaAuditing(auditorAwareRef="auditorProvider")
publicclassPersistenceConfig {
    
    ...
    
    @Bean
    AuditorAware<String> auditorProvider() {
        returnnewAuditorAwareImpl();
    }
    
    ...
    
}

基本讲得很清楚了。

使用也比较方便。

发表评论

电子邮件地址不会被公开。 必填项已用*标注