alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Hibernate example source code file (listeners.xml)

This example Hibernate source code file (listeners.xml) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Hibernate tags/keywords

an, an, calendar, date, jpa, lesser, license, public, public, this, this, xml, you, you

The Hibernate listeners.xml source code

<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2008, Red Hat Inc or third-party contributors as
  ~ indicated by the @author tags or express copyright attribution
  ~ statements applied by the authors.  All third-party contributions are
  ~ distributed under license by Red Hat Inc.
  ~
  ~ This copyrighted material is made available to anyone wishing to use, modify,
  ~ copy, or redistribute it subject to the terms and conditions of the GNU
  ~ Lesser General Public License, as published by the Free Software Foundation.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
<chapter id="listeners">
  <title>Entity listeners and Callback methods

  <section>
    <title>Definition

    <para>It is often useful for the application to react to certain events
    that occur inside the persistence mechanism. This allows the
    implementation of certain kinds of generic functionality, and extension of
    built-in functionality. The JPA specification provides two related
    mechanisms for this purpose.</para>

    <para>A method of the entity may be designated as a callback method to
    receive notification of a particular entity life cycle event. Callbacks
    methods are annotated by a callback annotation. You can also define an
    entity listener class to be used instead of the callback methods defined
    directly inside the entity class. An entity listener is a stateless class
    with a no-arg constructor. An entity listener is defined by annotating the
    entity class with the <literal>@EntityListeners
    annotation:</para>

    <programlisting role="JAVA" language="JAVA">@Entity
@EntityListeners(class=Audit.class)
public class Cat {
    @Id private Integer id;
    private String name;
    private Calendar dateOfBirth;
    @Transient private int age;
    private Date lastUpdate;
    //getters and setters

    /**
     * Set my transient property at load time based on a calculation,
     * note that a native Hibernate formula mapping is better for this purpose.
     */
    @PostLoad
    public void calculateAge() {
        Calendar birth = new GregorianCalendar();
        birth.setTime(dateOfBirth);
        Calendar now = new GregorianCalendar();
        now.setTime( new Date() );
        int adjust = 0;
        if ( now.get(Calendar.DAY_OF_YEAR) - birth.get(Calendar.DAY_OF_YEAR) < 0) {
            adjust = -1;
        }
        age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR) + adjust;
    }
}

public class LastUpdateListener {
    /**
     * automatic property set before any database persistence
     */
    @PreUpdate
    @PrePersist
    public void setLastUpdate(Cat o) {
        o.setLastUpdate( new Date() );
    }
}</programlisting>

    <para>The same callback method or entity listener method can be annotated
    with more than one callback annotation. For a given entity, you cannot
    have two methods being annotated by the same callback annotation whether
    it is a callback method or an entity listener method. A callback method is
    a no-arg method with no return type and any arbitrary name. An entity
    listener has the signature <code>void <METHOD>(Object) where
    Object is of the actual entity type (note that Hibernate Entity Manager
    relaxed this constraint and allows <literal>Object of
    <literal>java.lang.Object type (allowing sharing of listeners
    across several entities.)</para>

    <para>A callback method can raise a
    <classname>RuntimeException. The current transaction, if any,
    must be rolled back. The following callbacks are defined:</para>

    <table>
      <title>Callbacks

      <tgroup cols="2">
        <thead>
          <colspec colname="c1" colwidth="1*" />

          <colspec colname="c2" colwidth="3*" />

          <row>
            <entry align="center">Type

            <entry align="center">Description
          </row>
        </thead>

        <tbody>
          <row>
            <entry>@PrePersist

            <entry>Executed before the entity manager persist operation is
            actually executed or cascaded. This call is synchronous with the
            persist operation.</entry>
          </row>

          <row>
            <entry>@PreRemove

            <entry>Executed before the entity manager remove operation is
            actually executed or cascaded. This call is synchronous with the
            remove operation.</entry>
          </row>

          <row>
            <entry>@PostPersist

            <entry>Executed after the entity manager persist operation is
            actually executed or cascaded. This call is invoked after the
            database INSERT is executed.</entry>
          </row>

          <row>
            <entry>@PostRemove

            <entry>Executed after the entity manager remove operation is
            actually executed or cascaded. This call is synchronous with the
            remove operation.</entry>
          </row>

          <row>
            <entry>@PreUpdate

            <entry>Executed before the database UPDATE operation.
          </row>

          <row>
            <entry>@PostUpdate

            <entry>Executed after the database UPDATE operation.
          </row>

          <row>
            <entry>@PostLoad

            <entry>Executed after an entity has been loaded into the current
            persistence context or an entity has been refreshed.</entry>
          </row>
        </tbody>
      </tgroup>
    </table>

    <para>A callback method must not invoke
    <classname>EntityManager or Query
    methods!</para>
  </section>

  <section>
    <title>Callbacks and listeners inheritance

    <para>You can define several entity listeners per entity at different
    level of the hierarchy. You can also define several callbacks at different
    level of the hierarchy. But you cannot define two listeners for the same
    event in the same entity or the same entity listener.</para>

    <para>When an event is raised, the listeners are executed in this
    order:</para>

    <itemizedlist>
      <listitem>
        <para>@EntityListeners for a given entity or
        superclass in the array order</para>
      </listitem>

      <listitem>
        <para>Entity listeners for the superclasses (highest first)
      </listitem>

      <listitem>
        <para>Entity Listeners for the entity
      </listitem>

      <listitem>
        <para>Callbacks of the superclasses (highest first)
      </listitem>

      <listitem>
        <para>Callbacks of the entity
      </listitem>
    </itemizedlist>

    <para>You can stop the entity listeners inheritance by using the
    <literal>@ExcludeSuperclassListeners, all superclasses
    <literal>@EntityListeners will then be ignored.
  </section>

  <section>
    <title>XML definition

    <para>The JPA specification allows annotation overriding through JPA
    deployment descriptors. There is also an additional feature that can be
    useful: default event listeners.</para>

    <programlisting role="XML" language="XML"><?xml version="1.0" encoding="UTF-8"?>

<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
                 version="2.0"
        >
    <persistence-unit-metadata>
        <persistence-unit-defaults>
            <entity-listeners>
                <entity-listener class="org.hibernate.ejb.test.pack.defaultpar.IncrementListener">
                    <pre-persist method-name="increment"/>
                </entity-listener>
            </entity-listeners>
        </persistence-unit-defaults>
    </persistence-unit-metadata>
    <package>org.hibernate.ejb.test.pack.defaultpar</package>
    <entity class="ApplicationServer">
        <entity-listeners>
            <entity-listener class="OtherIncrementListener">
                <pre-persist method-name="increment"/>
            </entity-listener>
        </entity-listeners>


        <pre-persist method-name="calculate"/>
    </entity>
</entity-mappings></programlisting>

    <para>You can override entity listeners on a given entity. An entity
    listener correspond to a given class and one or several event fire a given
    method call. You can also define event on the entity itself to describe
    the callbacks.</para>

    <para>Last but not least, you can define some default entity listeners
    that will apply first on the entity listener stack of all the mapped
    entities of a given persistence unit. If you don't want an entity to
    inherit the default listeners, you can use
    <classname>@ExcludeDefaultListeners (or
    <exclude-default-listeners/>).</para>
  </section>
</chapter>

Other Hibernate examples (source code examples)

Here is a short list of links related to this Hibernate listeners.xml source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.