Spring Boot JPA Interceptor Guide: @PrePersist, @PreUpdate & Hibernate API
An Interceptor in Spring Data JPA allows you to modify queries, track changes, log operations, or enforce business rules dynamically.
Steps to Implement Interceptor in Spring Data JPA
- Create a Spring Boot Application
- Define an Entity
- Create a Repository
- Implement a JPA Interceptor (Entity Listener or Hibernate Interceptor)
- Register the Interceptor in Spring Boot
1. Create a Spring Boot Application
Create a Spring Boot project using Spring Initializr with dependencies:
- Spring Web
- Spring Data JPA
- H2 Database (for testing)
2. Define an Entity
Let's define a simple Product
entity.
3. Create a Repository
4. Implement an Interceptor
There are two approaches to intercept changes:
(A) Using EntityListeners
with @PrePersist
and @PreUpdate
(B) Using Hibernate’s Interceptor
API
(A) Entity Listeners - Simple Approach
This is useful if you want to trigger logic before persisting or updating an entity.
@PrePersist
: Called before inserting a new row.@PreUpdate
: Called before updating an existing row.
This approach does not require Hibernate dependencies.
(B) Hibernate Interceptor
- Advanced Approach
If you want deeper control, like modifying queries at runtime, log SQL statements, or apply dynamic changes, use a Hibernate Interceptor.
Step 1: Create Custom Hibernate Interceptor
onSave
: Triggers when an entity is saved.onFlushDirty
: Triggers when an entity is updated.
Step 2: Register Interceptor in Hibernate Properties
To register the interceptor, override LocalSessionFactoryBean
.
5. Testing the Interceptor
Create a simple REST controller to test.
6. Running the Application
- Run the Spring Boot application.
- Use Postman or cURL to test.
Insert a Product
💡 Interceptor will set price to 100.0 if it's null!
Get All Products
Conclusion
- If you need basic lifecycle hooks, use
@PrePersist
and@PreUpdate
. - If you need deep control over Hibernate queries, use
EmptyInterceptor
.