Spring Data JPA 从入门到精通~Auditing及其事件详解

 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值