Posts

Showing posts with the label @PreUpdate & Hibernate API

Spring Boot JPA Interceptor Guide: @PrePersist, @PreUpdate & Hibernate API

Image
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. package com.example.interceptor.model; import jakarta.persistence.*; @Entity @EntityListeners(ProductInterceptor.class) // Attach the interceptor public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Double price; // Getters and Setters public Long getId() { return id; } p...