The Row Says 'system': Spring Data JPA Auditing Outside the HTTP Request
Every table in our platform has the same four columns at the end: created_by , created_at , updated_by , updated_at . Spring Data JPA fills them in for you with four annotations and one @EnableJpaAuditing . That part takes five minutes. Then you look at the data a month later and find rows that say system , and you cannot tell which ones deserved it. Some of them really were written by a…
The article discusses the challenges of implementing audit trails in a multi-service platform using Spring Data JPA. The key points are:
1. Every table in the platform has four common columns: created_by, created_at, updated_by, updated_at. Spring Data JPA automatically fills these columns using annotations and the @EnableJpaAuditing configuration.
2. However, relying solely on Spring Data JPA for auditing can lead to issues when trying to identify the auditor for certain types of rows, such as those written by scheduled jobs, queue consumers, or @Async methods.
3. The article provides a solution where the auditor's identity is obtained from a session-scoped bean (CurrentUser) that holds the logged-in user's ID. This bean is shared across services and accessible in a singleton scope.
4. The example configuration demonstrates how to enable JPA auditing with minimal setup using @EnableJpaAuditing.
5. The article also discusses the importance of using Instant instead of LocalDateTime for timestamps to ensure timezone consistency across services.
6. Additionally, it highlights the need for an AuditorAware implementation that returns the correct auditor information based on the current thread's context, while avoiding pitfalls like null or incorrect auditor values on non-request threads.
In summary, the article provides a practical approach to implementing effective auditing in a multi-service architecture using Spring Data JPA, while addressing the challenges of identifying the correct auditor for different types of operations.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.