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:
@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:
@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.
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.