Spring Security不是必须的,这里使用它来获取用户名。配置的用户为:
spring.security.user.name=pkslow
spring.security.user.password=123456
2.2 创建实体父类
==========
其实父类不是必须的,你可以在每个想Audit的实体类进行配置,但比较麻烦,不如创建一个父类,再让想审计的子类都继承它:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class Auditable {
@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 {
@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 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);
};
}
}
这里配置的是通过Spring Security的Context来获取登陆用户的名字,当然可以有其它方案,如获取请求头的某个字段等。
注意注解@EnableJpaAuditing开启了审计功能。
2.4 测试
======
我们通过一个Controller来新增数据,看看会有什么效果:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
pri
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
vate UserRepository userRepository;
@PostMapping
public User save(@RequestBody User user) {
return userRepository.save(user);
}
}
通过curl命令来测试如下:
$ curl ‘http://localhost:8088/user’ -X POST
-H ‘Content-Type: application/json’
-H ‘Authorization:Basic cGtzbG93OjEyMzQ1Ng==’
-d '{
"name":"larry",
"email":"admin@pkslow.com",
"country":"China",
"website":"www.pkslow.com"
}’
{“createdBy”:“pkslow”,“createdDate”:“2021-01-15T15:08:47.035+0000”,“lastModifiedBy”:“pkslow”,“lastModifiedDate”:“2021-01-15T15:08:47.035+0000”,“userId”:7,“name”:“larry”,“email”:“admin@pkslow.com”,“country”:“China”,“website”:“www.pkslow.com”}
查看数据库,已经生成了审计记录:
3 总结
====
代码请查看:https://github.com/LarryDpk/pkslow-samples
原文链接:https://www.pkslow.com/archives/spring-data-jpa-audit
如果觉得本文对你有帮助,可以关注一下我公众号,回复关键字【面试】即可得到一份Java核心知识点整理与一份面试大礼包!另有更多技术干货文章以及相关资料共享,大家一起学习进步!



