Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Entity LifeCycle Callback Methods Srikanth Technologies Page : 1 Entity LifeCycle Callback methods A method may be designated as a lifecycle callback method to receive notification of entity lifecycle events. A lifecycle callback method may be defined on an entity class, a mapped superclass, or an entity listener class associated with an entity or mapped superclass. An entity listener class is a class whose methods are invoked in response to lifecycle events on an entity. Default entity listeners - entity listeners that apply to all entities in the persistence unit - can be specified by means of the XML descriptor. Lifecycle callback methods may throw unchecked/runtime exceptions. A runtime exception thrown by a callback method that executes within a transaction causes that transaction to be rolled back. Lifecycle callbacks can invoke JNDI, JDBC, JMS, and enterprise beans. When invoked from within a Java EE environment, the callback listeners for an entity share the enterprise naming context of the invoking component, and the entity callback methods are invoked in the transaction and security contexts of the calling component at the time at which the callback method is invoked. Where do we define callback methods? They may be defined directly on an entity class or mapped superclass with the following signature. void <METHOD>() @Entity public class Magazine { @Id private int id; @PostPersist public void doAfterPersist{ // do something } @PreDelete public void logDeletion() { System.out.println("deleting magazine with id “ + id); } } In an XML mapping file, we can define the same methods without annotations: <entity class="Magazine"> <pre-remove>logDeletion</pre-remove> <post-persist>doAfterPersist</post-load> </entity> Entity lifecycle callback methods can be defined on an entity listener class. In this case methods are of the following signature. void <METHOD>(Object) The Object argument is the entity instance for which the callback method is invoked. It may be declared as the actual entity type. @Entity @EntityListeners({MagazineLogger.class, ... }) public class Magazine { ... } public class MagazineLogger { @PostPersist public void logAddition(Object pc) { // code } Entity LifeCycle Callback Methods Srikanth Technologies Page : 2 @PreRemove public void logDeletion(Object pc) { // code } } In XML, we define both the listeners and their callback methods as so: <entity class="Magazine"> <entity-listeners> <entity-listener class="MagazineLogger"> <post-persist>logAddition</post-persist> <pre-remove>logDeletion</pre-remove> </entity-listener> </entity-listeners> </entity> Annotations related to entity lifecycle callback The following are the annotations that can be used to create lifecycle callback methods. @PrePersist Methods marked with this annotation will be invoked BEFORE an object is persisted. This could be used for assigning primary key values to persistent objects. This is equivalent to the XML element tag pre-persist. @PostPersist Methods marked with this annotation will be invoked AFTER an object has transitioned to the persistent state. You might want to use such methods to update a screen after a new row is added. This is equivalent to the XML element tag post-persist. @PreRemove Methods marked with this annotation will be invoked BEFORE an object transaction to the DELETED state. Access to persistent fields is valid within this method. You might use this method to cascade the deletion to related objects based on complex criteria, or to perform other cleanup. This is equivalent to the XML element tag pre-remove. @PostRemove Methods marked with this annotation will be invoked AFTER an object has been marked as to be deleted. This is equivalent to the XML element tag post-remove. @PreUpdate Methods marked with this annotation will be invoked just the persistent values in your objects are flushed to the datastore. This is equivalent to the XML element tag pre-update. @PreUpdate is the complement to @PostLoad. While methods marked with @PostLoad are most often used to initialize non-persistent values from persistent data, methods annotated with @PreUpdate is normally used to set persistent fields with information cached in non-persistent data. @PostUpdate Methods marked with this annotation will be invoked AFTER changes to a given instance have been stored to the datastore. This is useful for clearing stale data cached at the application layer. This is equivalent to the XML element tag post-update. @PostLoad: Methods marked with this annotation will be invoked after all eagerly fetched fields of your class have been loaded from the datastore. No other persistent fields can be accessed in this method. This is equivalent to the XML element tag post-load. @PostLoad is often used to initialize non-persistent fields whose values depend on the values of persistent fields, such as a complex datastructure. Entity LifeCycle Callback Methods Srikanth Technologies Page : 3 Order of invocation Default listeners, if any, are invoked first, in the order specified in the XML descriptor Super class listener are called before listeners of subclass If MULTIPLE classes in an inheritance hierarchy - entity classes and/or mapped superclasses - define entity listeners, the listeners defined for a SUPERCLASS are invoked BEFORE the listeners defined for its subclasses in this order. Excluding Listeners You can exclude default listeners and listeners defined in super classes from the invocation chain through the use of two class-level annotations: ExcludeDefaultListeners: This annotation indicates that no default listeners will be invoked for this class, or any of its subclasses. The XML equivalent is the empty exclude-default-listeners element. ExcludeSuperclassListeners: This annotation will cause JPA to skip invoking any listeners declared in superclasses. The XML equivalent is empty the exclude-superclass-listeners element. A Complete Example The following example demonstrates how to configure and define Book entity along with lifecycle callback methods. I used ORM.XML file here to define default entity listener as well as for entity mapping. Persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="ormPU" transaction-type="RESOURCE_LOCAL"> <provider>oracle.toplink.essentials.PersistenceProvider</provider> <mapping-file>orm/orm.xml</mapping-file> <properties> <property name="toplink.jdbc.user" value="jpa"/> <property name="toplink.jdbc.password" value="jpa"/> <property name="toplink.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:xe"/> <property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/> <property name="toplink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence> ORM.XML - must be placed in orm package for this example <?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 http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0"> <description>ORM Demo</description> <persistence-unit-metadata> <persistence-unit-defaults> <entity-listeners> <entity-listener class="orm.EntityListener"> <post-persist method-name="allPostPersist" /> </entity-listener> </entity-listeners> </persistence-unit-defaults> </persistence-unit-metadata> Entity LifeCycle Callback Methods Srikanth Technologies <package>orm</package> <entity class="orm.Book" name="Book"> <table name="Books"/> <entity-listeners> <entity-listener class="orm.EntityListener"> <post-persist method-name="postPersist" /> </entity-listener> </entity-listeners> <attributes> <id name="id"> <generated-value strategy="AUTO"/> </id> <basic name="title"> <column name="TITLE" length="100"/> </basic> </attributes> </entity> </entity-mappings> Book.java package orm; import java.io.Serializable; public class Book implements Serializable { private int id; private String title; public void setId(int id) { this.id = id; } public int getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } EntityListener.java package orm; public class EntityListener { public void postPersist(Book b) { if ( b.getTitle().length() < 5 ) { throw new RuntimeException("Invalid Title"); } System.out.println( "Persisted Book :" + b.getTitle() ); } public void allPostPersist(Object o) { System.out.println(" All post persist " + o.toString()); } } Page : 4 Entity LifeCycle Callback Methods Srikanth Technologies BookManager.java import import import import import javax.persistence.EntityManager; javax.persistence.EntityManagerFactory; javax.persistence.EntityTransaction; javax.persistence.Persistence; orm.Book; public class BookManager { static EntityManager em; public static void main(String args[]) { EntityManagerFactory emf; emf = Persistence.createEntityManagerFactory("ormPU"); em = emf.createEntityManager(); Book b = new Book(); b.setTitle("Pro"); // persist team objects EntityTransaction et = em.getTransaction(); et.begin(); em.persist(b); et.commit(); em.close(); } } Page : 5