JPA default entity listener

The problem

Sometimes we want to register a default Entity Listeners which are called as soon an entity is persisted, without adding the @EntityListeners annotation to our classes, as in most cases we anyway provide interfaces so we can access data on the entity itself. The problem is, that we cannot annotate our entity listener with any annotation, only the entity itself.

Solution

In JPA we can provide a entity mappings in the orm.xml which allows us to define default listeners which are executed on any entity.

Furthermore the body of the entity-listener may contain elements pre-persist to define method.

Example On GitHub

Example

Lets assume we want to add to each entity a update time and a create time. We could of course implement a base entity, but as we should favor composition over inheritance — which would allow us to add even more common fields to the entity — we want to go with a embedded class. Lets say TimestampBE.

Embeddable time stamps

This class adds to any entity the create date and update date. We just store UTC longs measured from 1970-01-01T00:00Z.

Tag interface

Next we add a interface which allows us to tag any entity that it has a time stamp.

Timestamp Entity Listener

Now we have to define the  behavior which sets us the create and update date in the live cycle of the entity.

Reister the default listener

Add a the src/main/resources/META-INF/orm.xml and register the Listener above. Adjust the package as needed:

Use the new classes

In the end you may add the new class at any entity:

 

Paul Sterl has written 17 articles

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">