jpa lifecycle events practice

10
JPA Lifecycle Events Practice Albert [email protected]

Upload: guo-albert

Post on 19-May-2015

848 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: JPA lifecycle events practice

JPA Lifecycle Events Practice

[email protected]

Page 2: JPA lifecycle events practice

Lifecycle Callbacks It is often necessary to perform various

actions at different stages of a persistent object's 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.

Page 3: JPA lifecycle events practice

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).

Page 4: JPA lifecycle events practice

Using Callback Methods

Page 5: JPA lifecycle events practice

Using Entity Listeners

Multiple listener classes can also be attached to one entity class

The listener class is attached to the entity class using the @EntityListeners  annotation

Page 6: JPA lifecycle events practice

Example

Page 7: JPA lifecycle events practice

NIG005W

User uses this function to maintain organization information.

Page 8: JPA lifecycle events practice

Schema

We intend to utilize JPA callback method to write user id and update timestamp into database automatically to ease programmers’ efforts.

Page 9: JPA lifecycle events practice

Using Callback MethodsMultiple events can be assigned to a single method as well. This method Will be triggered before insert and update.

Page 10: JPA lifecycle events practice

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.