JPA - Part 3
Go to Part 1.
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
Example:
@Entity
@EntityListeners(EmployeeListener.class)
public class Employee {
.....
}
public class EmployeeListener {
@PrePersist
public void beforePersist(Employee e) {
System.out.println("Before persist");
}
}
Merge Method
- Used to synchronise the changes between objects and database tables.
- Adds a new row if the entity is not present in db table.
- Updates the existing row if it is present in table.
Example:
et.begin();
....
....
em.merge(empObject); //merges the changes in empObject with table
et.commit();