關於自動填充或更新實體中的 CreateDate、CreatedBy 等在之前有一篇 jeecg 默認為空的字段值是如何被填充的? 有提到通過攔截器的方式實現,但是今天帶大家了解一下如果使用 JPA 的審計功能是如何簡單實現該操作的。
JPA Audit 說明
在 Spring JPA 中,支持在字段或者方法上進行注解 @CreateDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy
@CreateDate
表示該字段為創建時間時間字段,在這個實體被 insert 的時候,會設置默認值
@CreatedBy
表示該字段為創建人,在這個實體被insert的時候,會設置值。
@LastModifiedDate、@LastModifiedBy同理。
附一張項目中的使用圖:

如何使用審計?
難道就像上方圖片顯示的,只需要加上注解就可以了嗎?
顯然是否定的。
-
實體類上添加 @EntityListeners(AuditingEntityListener.class)
-
在需要的字段上加上 @CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 等注解。
-
在Xxx Application 啟動類上添加 @EnableJpaAuditing
-
實現 AuditorAware 接口來返回你需要插入的值。重點!
如下是一個基類的代碼,實現了 1、2 步:
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@ApiModelProperty(value = "唯一標識")
private String id;
@CreatedBy
private String createBy;
@CreatedDate
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "創建時間")
private Date createTime;
@ApiModelProperty(value = "更新者")
@LastModifiedBy
private String updateBy;
@LastModifiedDate
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "更新時間")
private Date updateTime;
}
第3步,啟動類上增加注釋:
@SpringBootApplication
@EnableJpaAuditing
public class TmaxApplication {
public static void main(String[] args) {
SpringApplication.run(TmaxApplication.class, args);
}
/**
* 測試中如果無法自動識別,可能是包路徑的問題,采用手動聲明bean的方式
* @return
*/
@Bean
public UserAuditor setUserAuditorAware(){
return new UserAuditor();
}
}
經過測試如果你的實體類上面的多個字段使用了 @CreatedBy 這樣的注解,只會有一個生效,也就是說在一次請求中,只會被調用一次
來看第4步,也是最重要的一步:
@Configuration
@Slf4j
public class UserAuditor implements AuditorAware<String> {
/**
* 獲取當前創建或修改的用戶
* @return
*/
@Override
public Optional<String> getCurrentAuditor() {
UserDetails user;
try {
user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return Optional.ofNullable(user.getUsername());
}catch (Exception e){
return Optional.empty();
}
}
}
關於方法 getCurrentAuditor 中獲取用戶名的操作可根據自己實際情況書寫,比如上方我用到的是 Spring Secirity 的一種寫法。
如果文章有錯的地方歡迎指正,大家互相留言交流。習慣在微信看技術文章,想要獲取更多的Java資源的同學,可以關注微信公眾號:niceyoo
