As of now we have learned about entities, relationships, inheritance and how entity manager performs operations on them. Till now, entities played a passive part. What if we want entities to perform something when some operations are performed on them? How can we listen to the events performed on entities? We can write JPA lifecycle callback methods by making use of annotations.
JPA Lifecycle Callback methods:
Here are JPA lifecycle callback methods:
- @PrePersist :- Entity is notified when em.persist() is successfully invoked on entity.
- @PostPersist :- Notified when entity is persted in database.
- @PreUpdate :- Notified when entity is modified.
- @PostUpdate :- Notified when updated state of entity is inserted in database
- @PreRemove :- Notified when remove operation is called for entity by entity manage.r
- @PostRemove:- Notified when entity is deleted from database.
Some rules need to be followed when annotating a method as jpa lifecycle callback methods.
- They can have any name
- The method signature should be such that return type is void and there are no parameters.
- They can have any access i.e. they can be private, default, protected or public.
- They cannot throw any checked exceptions.
We’ve seen a little description about jpa lifecycle callback methods, let us directly test them out.
We have employee table as below.
Corresponding Employee entity
Run this using code below.
This gives output as follows.
Invoked before persisting employee
Invoked after persisting employee
Invoked before updating employee
Invoked after updating employee
Invoked before removing employee
Invoked after removing employee
I hope this example helped understand jpa lifecycle callback methods, in next article, we will see how we can create entity listeners such that we do not need to modify entities
References for further study :