Callback methods are user defined methods that are attached to Entity lifecycle events and are invoked automatically by JPA when these events occur. Callback methods can be embedded into the Entity class or in an external class:

Here is an example of Entity annotated with callback methods:


public static class EntityExampleCallbacks {

@PrePersist void onPrePersist() {}

@PostPersist void onPostPersist() {}

@PostLoad void onPostLoad() {}

@PreUpdate void onPreUpdate() {}

@PostUpdate void onPostUpdate() {}

@PreRemove void onPreRemove() {}

@PostRemove void onPostRemove() {}


And here's a description of the single callback annotations:

The annotation specifies when the callback method is invoked:

@PrePersist - before a new entity is persisted (added to the EntityManager).

@PostPersist - after storing a new entity in the database (during commit or flush).

@PostLoad - after an entity has been retrieved from the database.

@PreUpdate - when an entity is identified as modified by the EntityManager.

@PostUpdate - after updating an entity in the database (during commit or flush).

@PreRemove - when an entity is marked for removal in the EntityManager.

@PostRemove - after deleting an entity from the database (during commit or flush).


 Note that you can apply multiple callback annotations to a method, but you can use each annotation just once per Entity


You can as well define your listeners in an external class, like this:

public class MyEntityListener {

@PrePersist void onPrePersist(Object o) {}

@PostPersist void onPostPersist(Object o) {}

@PostLoad void onPostLoad(Object o) {}

@PreUpdate void onPreUpdate(Object o) {}

@PostUpdate void onPostUpdate(Object o) {}

@PreRemove void onPreRemove(Object o) {}

@PostRemove void onPostRemove(Object o) {}


And here's how to attach a listener to an Entity using the @EntityListeners annotation:

@Entity @EntityListeners(MyEntityListener .class)

public class EntityExampleCallbacks  {