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

– 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

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();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s