Monday, 20 August 2012

JPA Lifecycle Annotations

This post illustrates how to use JPA's life cycle annotations. These can be used on method to perform actions before or after CRUD operations. The code example is available from Github in the JPA directory.

We define two classes, one with annotations WithLifeCycleAnnotations and one without annotations NoLifeCycleAnnotations. This example operates Hibernate JPA in a standalone in-memory mode.

With annotations:
public class WithLifeCycleAnnotations {

    private long ID;

    private String name = "";

    public void postLoad() {
        System.out.println("Post Load called !!!");

    public void postPersist() {
        System.out.println("Post Persist called !!!");

    public void postRemove() {
        System.out.println("Post Remove called !!!");

    public void postUpdate() {
        System.out.println("Post Update called !!!");

    public void prePersist() {
        System.out.println("Pre Persist called !!!");

    public void preRemove() {
        System.out.println("Pre Remove called !!!");

    public void preUpdate() {
        System.out.println("Pre Update called !!!");

    // Setters & Getters...

The following:
NoLifeCycleAnnotations nlca = new NoLifeCycleAnnotations();

System.out.println("Saving NO lifecycle annotations");;

System.out.println("Reading NO lifecycle annotations");
NoLifeCycleAnnotations nlcaRetr =
    JPA.INSTANCE.get(NoLifeCycleAnnotations.class, nlca.getID());

System.out.println("Updating NO lifecycle annotations");

System.out.println("Deleting NO lifecycle annotations");

WithLifeCycleAnnotations wlca = new WithLifeCycleAnnotations();

System.out.println("Saving WITH lifecycle annotations:");;

System.out.println("Reading WITH lifecycle annotations:");
WithLifeCycleAnnotations wlcaRetr =
    JPA.INSTANCE.get(WithLifeCycleAnnotations.class, wlca.getID());

System.out.println("Updating WITH lifecycle annotations:");

System.out.println("Deleting WITH lifecycle annotations:");
Generates the following output:
Saving NO lifecycle annotations
Reading NO lifecycle annotations
Updating NO lifecycle annotations
Deleting NO lifecycle annotations

Saving WITH lifecycle annotations:
Pre Persist called !!!
Post Persist called !!!
Reading WITH lifecycle annotations:
Updating WITH lifecycle annotations:
Pre Update called !!!
Post Update called !!!
Deleting WITH lifecycle annotations:
Pre Remove called !!!
Post Remove called !!
For some reason, @PostLoad is not invoked when using JPA/Hibernate in standalone mode.

No comments:

Post a comment