Auditing 及其事件详解
Auditing 翻译过来是审计和审核,Spring 的优秀之处在于帮我们想到了很多繁琐事情的解决方案,我们在实际的业务系统中,针对一张表的操作大部分是需要记录谁什么时间创建的,谁什么时间修改的,并且能让我们方便的记录操作日志。Spring Data JPA 为我们提供了审计功能的架构实现,提供了四个注解专门解决这件事情:
- @CreatedBy 哪个用户创建的。
- @CreatedDate 创建的时间。
- @LastModifiedBy 修改实体的用户。
- @LastModifiedDate 最后一次修改时间。
Auditing 如何配置
我们以一个快速的例子,看看它是怎么配置生效的。
(1)先新建一个 @Entity:UserCustomerEntity 里面的写法如下。
@Entity
@Table(name = "user_customer", schema = "test", catalog = "")
@EntityListeners(AuditingEntityListener.class)
public class UserCustomerEntity {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@CreatedDate
@Column(name = "create_time", nullable = true)
private Date createTime;
@CreatedBy
@Column(name = "create_user_id", nullable = true)
private Integer createUserId;
@LastModifiedBy
@Column(name = "last_modified_user_id", nullable = true)
private Integer lastModifiedUserId;
@LastModifiedDate
@Column(name = "last_modified_time", nullable = true)
private Date lastModifiedTime;
@Column(name = "customer_name", nullable = true, length = 50)
private String customerName;
@Column(name = "customer_email", nullable = true, length = 50)
private String customerEmail;
......
}
@Entity 实体中我们需要做两点:
- 相应的字段添加 @CreatedBy、@CreatedDate、@LastModifiedBy and @LastModifiedDate注解。
- 增加 @EntityListeners(AuditingEntityListener.class)。
(2)实现 AuditorAware 接口告诉 JPA 当前的用户是谁。
实现 AuditorAware 接口,实现 getCurrentAuditor 方法,返回一个 Integer 的 user ID。以下代码介绍了两种做法:
public class MyAuditorAware implements AuditorAware<Integer> {
/**
* Returns