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
阅读 209 · 发布于 2023-02-27
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Rust 动态大小类型阅读 88
-
算法:迷宫问题-递归实现阅读 1544
-
Linux 之 -bash pecl command not found 的解决方法阅读 3962
-
JavaScript 判断字符串是否包含指定字符阅读 589
-
Android 给按钮添加水波纹效果阅读 4060
-
Ali OSS 抛出 NoSuchKey 错误阅读 149
-
Windows 子系统 WslRegisterDistribution failed with error: 0x80370102阅读 1512
-
Java jstat 监控远程服务阅读 1540
-
Android 根据包名启动 Activity阅读 2989
-
缓存穿透、缓存雪崩、缓存击穿、缓存污染阅读 2077