Menu

JPA: Part 3

Callback Methods

When insert, update and delete occurs, we can listen to those events and call some methods when such events occur. Callback methods should be prefixed by following annotations:

@PrePersist – called before persist()

@PostPersist – called after persist()

@PreRemove – called before remove()

@PostRemove – called after commit()

@PreUpdate – called before commit()

@PostUpdate – called after commit()

More than one annotation can applied to a single method. There should be only one method with a particular callback annotation(example, there shouldn’t be more than one @Prepersist methods). The callback methods shouldn’t take any arguments.

Entity Listeners

Mixing callback methods into Entity class is not a good practice. So we write it in another class which is an Entity Listener.

Annotations Used:

@EntityListeners(EntityListener_ClassName.class)

Used before the Entity class

– Entity Listener should have public default constructor
– An Entity class can have some callback methods defined in it and some in an Entity Listener
– An Entity Listener class can listen to more than one Entity classes.
– The callback methods defined in Entity Listener class must take an object of Entity class as argument