This page will provide JPA @EntityListeners example with callbacks @PrePersist, @PostPersist, @PostLoad, @PreUpdate, @PostUpdate, @PreRemove, @PostRemove. JPA @EntityListeners is used on entity or mapped superclass at class level. JPA provides callback methods for saving, fetching, updating and removing data from database. Here we will use JPA EntityManager to interact with database.

JPA @EntityListeners

@EntityListeners annotation specifies the callback listener classes . This annotation can be used for an entity or mapped superclass.
1. To configure single callback listener class, we can do as follows.

@EntityListeners(UserListener.class)
public class User {}

2. To configure multiple callback listener classes, we can do as follows.

JPA Callbacks Method

JPA provides callback methods to listen saving, fetching, updating and removing data from database. These callback methods annotated in a listener bean class must have return type void and accept one argument.

@PrePersist: The method annotated with @PrePersist in listener bean class is called before persisting data by entity manager persist() method.

@PostPersist: The method annotated with @PostPersist is called after persisting data.

@PostLoad: The method annotated with @PostLoad is called after fetching data using entity manager find() method in persistence context or refreshing it with database by using refresh() method. If the entity instance is already loaded in persistence context, then calling of find() method will not call @PostLoad.

@PreUpdate: The method annotated with @PreUpdate in listener bean class is called before updating data.

@PostUpdate: It is called after updating data.

@PreRemove: The method annotated with @PreRemove in listener bean class is called before removing data by using entity manager remove() method.

@PostRemove: It is called after removing data.

Database Schema

For the demo we are using a table with following schema created in MySQL.
Table: user