简体   繁体   中英

JPA 2: How many methods are allowed in one entity with @Prepersist annotation?

In JPA 2, how many methods can be declared with annotations like @PrePersist and in which order these methods are executed? Sometimes we also create different class for listener and apply this class on entity using @EntityListener annotation and we also declare methods in entity, so what is the order of execution of these methods?

Regarding the order of invocation the JPA 2 spec section 3.5 states:

If multiple entity listeners are defined, the order in which they are invoked is determined by the order in which they are specified in the EntityListeners annotation. The XML descriptor may be used as an alternative to specify the invocation order of entity listeners or to override the order specified in metadata annotations.

And regarding wether using multiple methods for the same lifecycle event the JPA 2 Spec states in section 3.5:

A single class must not have more than one lifecycle callback method for the same lifecycle event. The same method may be used for multiple callback events.

A @PrePersist annotated method can be declared on:

  • an entity class or any of its entity or mapped superclasses
  • on default listeners declared globally on the XML descriptor
  • on listeners referenced with the @EntityListener anotation in the entity class and any of his entity or mapped superclasses.

The order is defined in the 3.5.5 section of the JPA 2.2 spec (3.5.4 in the JPA 2.0 spec), and summarized it would be:

  1. Global listeners in the order they are defined in the XML descriptor
  2. @EntityListeners defined in the order they appear on the annotation on the entity classes. If there is an entity hieararchy listeners referenced on superclasses are executed before the listeners referenced in the subclasses.
  3. Lifecycle method on the entity classes. If there is an entity hieararchy, lifecycle methods declared on superclasses are executed before methods declared on subclasses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM