在Spring JPA中,支持在字段或方法上進行註解 @CreateDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy。具體含義:
**@CreateDate: ** 表示該字段是創建時間字段,在這個實體被insert的時候,會自動填充創建的時間,不用手動填充該字段。
**@CreatedBy: ** 表示該字段是創建人字段,在這個實體被insert的時候,會自動填充創建人字段,不用手動填充。
@LastModifiedDate、@LastModifiedBy同理。
如何實現自動填充功能,即如何使用審計?
1、在Xxx Application 啓動類上添加 @EnableJpaAuditing:開啓審計功能。
@EnableScheduling @EnableJpaAuditing //利用jpa可以給MySQL列屬性自動賦值,例如一些創建時間,修改時間 @EnableEurekaClient @SpringBootApplication public class CouponTemplateApplication { public static void main(String[] args) { SpringApplication.run(CouponTemplateApplication.class, args); } /** * 測試中如果無法自動識別,可能是包路徑的問題,採用手動聲明bean的方式 * @return */ @Bean public UserAuditor setUserAuditorAware(){ return new UserAuditor(); } }
2、實體類上添加 @EntityListeners(AuditingEntityListener.class):開啓實體類監聽。
3、在需要的字段上加上 @CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 等註解。
@Data @NoArgsConstructor @AllArgsConstructor @Entity //實體類 @EntityListeners(AuditingEntityListener.class) //監聽器,自動賦值創建時間 @Table(name = "coupon_template") @JsonSerialize(using = CouponTemplateSerialize.class) //綁定自定義的序列化器 public class CouponTemplate implements Serializable { /** 自增主鍵 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id",nullable = false) @Basic //指定屬於我們數據表的一個列,相反的@Transient,表示該列不屬於數據表 private Integer id; /** 是否是可用狀態 */ @Column(name = "available",nullable = false) private Boolean available; /** 是否過期 */ @Column(name = "expired",nullable = false) private Boolean expired; /** 優惠券名稱 */ @Column(name = "name",nullable = false) private String name; /** 優惠券 logo */ @Column(name = "logo",nullable = false) private String logo; /** 優惠券描述 */ @Column(name = "intro",nullable = false) private String desc; /** 優惠券模板 創建時間 * 使用@CreateDate註解在插入的時候,自動生成創建時間,與監聽註解有關 * */ @CreatedDate @Column(name = "create_time",nullable = false) private Date createTime; }
4、實現 AuditorAware 接口來返回你需要插入的值。重點!
@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(); } } }