Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JPA lifecycle events practice


Published on

  • Be the first to comment

JPA lifecycle events practice

  1. 1. JPA LifecycleEvents
  2. 2. Lifecycle Callbacks It is often necessary to perform various actions at different stages of a persistent objects lifecycle. JPA includes a variety of callbacks methods for monitoring changes in the lifecycle of your persistent objects. These callbacks can be defined on the persistent classes themselves and on non-persistent listener classes.
  3. 3. Callback MethodsCallback method Description@PrePersist before a new entity is persisted (added to the EntityManager).@PostPersist after storing a new entity in the database (during commit or flush).@PostLoad after an entity has been retrieved from the database.@PreUpdate when an entity is identified as modified by the EntityManager.@PostUpdate after updating an entity in the database (during commit or flush).@PreRemove when an entity is marked for removal in the EntityManager.@PostRemove after deleting an entity from the database (during commit or flush).
  4. 4. Using Callback Methods
  5. 5. Using Entity ListenersThe listener class is attached to the entity class using the@EntityListeners annotationMultiple listener classes can also be attached to one entity class
  6. 6. Example
  7. 7. NIG005WUser uses this function to maintain organization information.
  8. 8. SchemaWe intend to utilize JPA callback method to write user id and updatetimestamp into database automatically to ease programmers’ efforts.
  9. 9. Using Callback Methods Multiple events can be assigned to a single method as well. This method Will be triggered before insert and update.
  10. 10. Using Entity Listeners Mixing lifecycle event code into your persistent classes is not always ideal. It is often more elegant to handle cross-cutting lifecycle events in a non-persistent listener class. JPA allows for this, requiring only that listener classes have a public no-arg constructor. Like persistent classes, your listener classes can consume any number of callbacks. The callback methods must take in a single java.lang.Object argument which represents the persistent object that triggered the event.