Spring Data JPA的Audit功能審計(jì)數(shù)據(jù)庫的變更
我最新最全的文章都在 南瓜慢說 www.pkslow.com ,歡迎大家來喝茶!
1 數(shù)據(jù)庫審計(jì)
數(shù)據(jù)庫審計(jì)是指當(dāng)數(shù)據(jù)庫有記錄變更時,可以記錄數(shù)據(jù)庫的變更時間和變更人等,這樣以后出問題回溯問責(zé)也比較方便。對于審計(jì)表記錄的變更可以兩種方式,一種是建立一張審計(jì)表專門用于記錄,另一種是在數(shù)據(jù)庫增加字段。本文所討論的是第二種方案。
那如何在新增、修改、刪除的時候同時增加記錄呢?如果每張表都單獨(dú)記錄,代碼就會顯得很冗余。更好的方式應(yīng)該是做切面或者事件監(jiān)聽,當(dāng)數(shù)據(jù)有變更時統(tǒng)一進(jìn)行記錄。
2 Spring Data JPA審計(jì)
Spring Data JPA為我們提供了方便的Audit功能,通過四個注解來標(biāo)記字段:
(1) @CreatedBy: 創(chuàng)建人
(2) @CreatedDate: 創(chuàng)建時間
(3) @LastModifiedBy: 最后修改人
(4) @LastModifiedDate: 最后修改時間
接下來我們來看看怎么使用。
2.1 項(xiàng)目準(zhǔn)備
通過Docker啟動PostgreSQL數(shù)據(jù)庫:
docker run -itd \
--name pkslow-postgres \
-e POSTGRES_DB=pkslow \
-e POSTGRES_USER=pkslow \
-e POSTGRES_PASSWORD=pkslow \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-p 5432:5432 \
postgres:10
引入相關(guān)依賴:
<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 創(chuàng)建實(shí)體父類
其實(shí)父類不是必須的,你可以在每個想Audit的實(shí)體類進(jìn)行配置,但比較麻煩,不如創(chuàng)建一個父類,再讓想審計(jì)的子類都繼承它:
@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可以讓其它子實(shí)體類繼承相關(guān)的字段和屬性;
@EntityListeners設(shè)置監(jiān)聽類,會對新增和修改進(jìn)行回調(diào)處理。
有了父類之后,子類就簡單了:
@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 如何獲取名字
數(shù)據(jù)總是被修改的,我們要提供一個獲取修改人名字的接口,配置如下:
@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);
};
}
}
這里配置的是通過Spring Security的Context來獲取登陸用戶的名字,當(dāng)然可以有其它方案,如獲取請求頭的某個字段等。
注意注解@EnableJpaAuditing開啟了審計(jì)功能。
2.4 測試
我們通過一個Controller來新增數(shù)據(jù),看看會有什么效果:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private 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}
查看數(shù)據(jù)庫,已經(jīng)生成了審計(jì)記錄:

3 總結(jié)
代碼請查看:https://github.com/LarryDpk/pkslow-samples
到此這篇關(guān)于Spring Data JPA的Audit功能審計(jì)數(shù)據(jù)庫的變更的文章就介紹到這了,更多相關(guān)Spring Data JPA審計(jì)數(shù)據(jù)庫變更內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實(shí)現(xiàn)二維碼生成的幾個方法(推薦)
本篇文章主要介紹了java實(shí)現(xiàn)二維碼生成的幾個方法(推薦),具有一定的參考價值,有興趣的可以了解一下。2016-12-12
學(xué)習(xí)JVM之java內(nèi)存區(qū)域與異常
關(guān)于JVM內(nèi)存區(qū)域的知識對于初學(xué)者來說其實(shí)是很重要的,了解Java內(nèi)存分配的原理,這對于以后JAVA的學(xué)習(xí)會有更深刻的理解。下面來看看詳細(xì)介紹。2016-07-07
String.intern()作用與常量池關(guān)系示例解析
這篇文章主要為大家介紹了String.intern()作用與常量池關(guān)系示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
servlet之cookie簡介_動力節(jié)點(diǎn)Java學(xué)院整理
Cookie技術(shù)誕生以來,它就成了廣大網(wǎng)絡(luò)用戶和Web開發(fā)人員爭論的一個焦點(diǎn)。下面這篇文章主要給大家介紹了關(guān)于servlet之cookie簡介的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。2017-07-07
java數(shù)據(jù)結(jié)構(gòu)與算法之插入算法實(shí)現(xiàn)數(shù)值排序示例
這篇文章主要介紹了java數(shù)據(jù)結(jié)構(gòu)與算法之插入算法實(shí)現(xiàn)數(shù)值排序的方法,結(jié)合簡單實(shí)例形式分析了插入算法的節(jié)點(diǎn)操作與排序相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-08-08
Spring源碼學(xué)習(xí)之動態(tài)代理實(shí)現(xiàn)流程
這篇文章主要給大家介紹了關(guān)于Spring源碼學(xué)習(xí)之動態(tài)代理實(shí)現(xiàn)流程的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
基于java實(shí)現(xiàn)租車管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了基于java實(shí)現(xiàn)租車管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-12-12

