SpringDataJPA 的 Audit 功能,审计数据库的变更,springmvc 源码分析 pdf 百度云
2 Spring Data JPA 审计
===================
Spring Data JPA 为我们提供了方便的 Audit 功能,通过四个注解来标记字段:
(1) @CreatedBy: 创建人
(2) @CreatedDate: 创建时间
(3) @LastModifiedBy: 最后修改人
(4) @LastModifiedDate: 最后修改时间
接下来我们来看看怎么使用。
2.1 项目准备
========
通过 Docker 启动 PostgreSQL 数据库:
docker run -itd \
--name pkslow-postgres \
-e POSTGRES_DB=pkslow \
-e POSTGRES_USER=pkslow \
-e POSTGRES_PASSWORD=pkslow \
-e PGDATA=/var/lib/postgresql/d
ata/pgdata \
-p 5432:5432 \
postgres:10
引入相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Security 不是必须的,这里使用它来获取用户名。配置的用户为:
spring.security.user.name=pkslow
spring.security.user.password=123456
2.2 创建实体父类
==========
其实父类不是必须的,你可以在每个想 Audit 的实体类进行配置,但比较麻烦,不如创建一个父类,再让想审计的子类都继承它:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class Auditable<U> {
@CreatedBy
@Column(name = "created_by")
private U createdBy;
@CreatedDate
@Column(name = "created_date")
private Date createdDate;
@LastModifiedBy
@Column(name = "last_modified_by")
private U lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
private Date lastModifiedDate;
// getter
//setter
}
@MappedSuperclass 可以让其它子实体类继承相关的字段和属性;
@EntityListeners 设置监听类,会对新增和修改进行回调处理。
有了父类之后,子类就简单了:
@Entity
@Table(name = "pkslow_users")
public class User extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private String name;
private String email;
private String country;
private String website;
//getter setter
}
2.3 如何获取名字
==========
数据总是被修改的,我们要提供一个获取修改人名字的接口,配置如下:
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class JpaAuditingConfiguration {
@Bean
public AuditorAware<String> auditorProvider() {
return () -> {
String username = "system";
SecurityContext context = SecurityContextHolder.getContext();
if (context != null) {
Authentication authentication = context.getAuthentication();
if (authentication != null) {
username = authentication.getName();
}
}
String result = username;
return Optional.ofNullable(result);
};
评论