Saving Java EE. Nested @PostLoad. PostLoad callback method in supercars

What happens if both an entity class and its superclass implement methods annotated with javax.persistence.PostLoad ? Which method should be called and which one is the first? Is this due to the visibility of the method (private, public)?

(The Hibernate default session does not call such methods at all, and I'm going to implement a workaround using the Hibernate PostLoadEventListener .)

+4
source share
1 answer

Let me copy some parts of the Java Persistence API 2.0 FR specification that I believe can answer your question.

3.5.1 Lifecycle callback methods

Callback methods can have a public, private, secure, or packet level of access , but should not be static or final.

3.5.4 Several lifecycle callback methods for an object's lifecycle event

If several classes in the inheritance are hierarchical entity classes and / or associated superclasses - listeners define the object, listeners defined for the superclass are called before the listeners defined for their subclasses in this order .

(...)

If the lifecycle callback method for the same lifecycle event also specified in the entity class and / or one or more of its entities or associated superclasses, callback methods in the entity class and / or superclasses are called after other lifecycle callback methods, the most common superclass in the first place.

The following section provides a very detailed example that can solve your problem:

3.5.5 Example

There are several classes of entities and listeners for animals:

 @Entity public class Animal { .... @PostPersist protected void postPersistAnimal() { .... } } @Entity @EntityListeners(PetListener.class) public class Pet extends Animal { .... } @Entity @EntityListeners({CatListener.class, CatListener2.class}) public class Cat extends Pet { .... } public class PetListener { @PostPersist protected void postPersistPetListenerMethod(Object pet) { .... } } public class CatListener { @PostPersist protected void postPersistCatListenerMethod(Object cat) { .... } } public class CatListener2 { @PostPersist protected void postPersistCatListener2Method(Object cat) { .... } } 

If the PostPersist event occurs on a Cat instance, the following methods are called in order:
- postPersistPetListenerMethod
- postPersistCatListenerMethod
- postPersistCatListener2Method
- postPersistAnimal

Hope this helps!

+6
source

Source: https://habr.com/ru/post/1381460/


All Articles