Friday, April 15, 2011

Lifecycle Callback Methods in JPA

JPA contains different lifecycle methods for monitoring changes in the the lifecycle of persistent objects. Every event in JPA has a corresponding callback method marker. These markers are shared between callback methods and their listeners. In JPA, these markers can be used for creating methods for callbacks by annoatating that method with callback annoatations. The lifecycle method annoations in JPA are: @PrePersist , @PostPersist, @PreUpdate, @PostUpdate, @PreRemove , @PostRemove and @PostLoad

Following are the rules that apply to lifecycle callback methods in JPA:
  • Methods can have public, private, protected, or package-level access, but must not be static or final.
  • A method may be annotated with multiple life-cycle event annotations. However, only one life-cycle annotation of a given type may be present in an entity class (you can’t have two @PrePersist annotations in the same entity, for example).
  • A method can throw unchecked (runtime) exceptions but not checked exceptions. Throwing a runtime exception will roll back the transaction if one exists.
  • A method can invoke JNDI, JDBC, JMS, and EJBs but cannot invoke any EntityManager or Query operations.
  • With inheritance, if a method is specified on the superclass, it will get invoked before the method on the child class.
  • If event cascading is used in the relationships, the callback method will also get called in a cascaded way. For example, let’s say a Student has a collection of addresses, and a cascade remove is set on the relation. When you delete the student, the Address @PreRemove method would be invoked as well as the Customer @PreRemove method.

No comments: