# [Spring Data JPA] 自動存入時間和使用者 [TOC] - `@CreatedDate` 資料新增時會自動存入創建時間 - `@CreatedBy` 創建者 - `@LastModifiedDate` 最後修改時間 - `@LastModifiedBy` 最後修改者 ### :triangular_flag_on_post: **使用步驟** 1. 啟動類別加上注釋 `@EnableJpaAuditing` - Application ```=java @SpringBootApplication @EnableJpaAuditing(auditorAwareRef = "auditorAware") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 2. 需要自動生成的實體類別(@Entity)須加上注釋 `@EntityListeners(AuditingEntityListener.class)`,並在對應的變數(欄位)加上注釋 `@CreatedDate`、`@CreatedBy`、`@LastModifiedDate`、`@LastModifiedBy`。 - Entity ```=java @EntityListeners(AuditingEntityListener.class) public abstract class Auditable<T> { @CreatedBy @Column(name = "created_by") private T createdBy; @CreatedDate @Column(name = "created_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createdDate = new Date(); @LastModifiedBy @Column(name = "last_modified_by") private T lastModifiedBy; @LastModifiedDate @Column(name = "last_modified_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date lastModifiedDate = new Date(); } ``` 3. 現在時間會自動存入資料庫,但`@CreatedBy`和`@LastModifiedBy`因為沒有被賦值,欄位為空(null),必須實作AuditorAware介面的getCurrentAuditor()方法來傳回需要的值 - AuditorAware ```=java @Component("auditorAware") public class MyAuditorAware implements AuditorAware<String>{ @Override public Optional<String> getCurrentAuditor() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if(authentication == null || !authentication.isAuthenticated()) { return null; } return Optional.of(((MyUserDetails)authentication.getPrincipal()).getUsername()); } } ``` --- 參考資料: [Spring JPA 使用@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 自动生成时间和修改者 - 簡書](https://www.jianshu.com/p/14cb69646195) [3. Auditing - Part I. Reference Documentation](https://docs.spring.io/spring-data/jpa/docs/1.7.0.DATAJPA-580-SNAPSHOT/reference/html/auditing.html)
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.