Spring Boot JPA 开启审计字段自动注入
Spring Boot 大约 1390 字需求
对于一些审计字段,如:创建时间,更新时间,创建人,更新人。
注解
Spring
提供了这几种审计字段的注解,分别是:
@CreatedDate
:创建时间@LastModifiedDate
:最后修改时间@CreatedBy
:创建人@LastModifiedBy
:最后修改人
自动注入
需添加@EnableJpaAuditing
,启用审计字段自动注入,且在需要审计的实体类上添加@EntityListeners(AuditingEntityListener.class)
审计实体监听。
对于创建人和修改人,需要注入AuditorAware
对象,否则无法自动注入@CreatedBy
和@LastModifiedBy
。
代码
第一步
@EnableJpaAuditing
开启审计,auditorAwareRef
指定审计人。
对于Spring Security
可使用注释部分代码。
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class JpaAuditConfig {
@Bean
public AuditorAware<String> auditorProvider() {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null || !authentication.isAuthenticated()) {
// return null;
// }
// return ((User) authentication.getPrincipal()).getUsername();
return () -> Optional.of("unknown");
}
}
第二步
公共类上开启审计实体监听,字段上标注审计注解。
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class CommonEntity {
@CreatedDate
@Column
private LocalDateTime createTs;
@LastModifiedDate
@Column
private LocalDateTime updateTs;
@CreatedBy
@Column
private String createBy;
@LastModifiedBy
@Column
private String updateBy;
}
参考
https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html
阅读 510 · 发布于 2023-02-27
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Java 17 中使用 ScriptEngine 解析 JavaScript 脚本阅读 667
-
Java 并发编程之 LongAdder 源码解析阅读 1499
-
macOS 安装 Redis阅读 285
-
SpringMVC 请求流程阅读 1727
-
走进 Rust:打印结构体字段阅读 6517
-
Spring Boot Slf4j MDC 实现全链路日志追踪阅读 974
-
Docker WARNING IPv4 forwarding is disabled. Networking will not work阅读 1054
-
Linux CentOS 安装 MySQL5.7阅读 4367
-
设计模式之责任链模式阅读 2485
-
走进 Rust:Vector 集合阅读 1666