JPA EntityListeners

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

In previous article, we learned how jpa lifecycle call methods are used to listen to events about entities, but these methods need to be implemented in entity class itself. What if we don’t want to include callback methods in entity classes? We can use jpa entitylisteners for this purpose.

JPA EntityListeners:

Jpa entitylisteners are not entities, they are simply java classes in which jpa lifecycle callback methods are implemented using annotations. Some points to note about jpa entitylisteners are:

  • The listener class should have access to entity.
  • Hence, method signature of callback method should have a single parameter that is compatible with the entity it listens to.
  • JPA entitylisteners should have a public no arg constructor.

When attaching jpa entitylisteners to entities, these things are followed.

  • Entities should defines entitylisteners using annotation @EntityListeners
  • Multiple listeners can be listed.
  • Whenever a lifecycle event occurs, provider iterates through the list of all jpa entitylisteners listed in @EntityListeners annotation and instantiates them in the order they are listed.
  • Provider invokes callback methods of listener and passes entity instance to it.
  • Callback methods from entity are invoked if there are any.

Let us see an example.

Employee table in database

EmployeeTable

Employee.java

EmployeeLoggerListener.java

Test this out using code below.

This persists the employee in database and prints out following.

persisting employee with id = 10
Persisted employee with id = 10
Updating employee with id = 10
Updated employee with id = 10
Removing employee with id = 10
Removed employee with id = 10

I hope this example helped understand jpa entitylisteners.

References for further study :

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

One thought on “JPA EntityListeners

  • June 7, 2017 at 4:57 am
    Permalink

    Is there any difference in implementation when using SessionFactory. I am using the same with HibernateUtil Configuration Class. It doesn’t Works. If you could , please help me.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *