Java EE 持久性。嵌套@PostLoad。 supercalss中的PostLoad回调方法

标签 java hibernate jakarta-ee jpa superclass

如果实体类及其父类(super class)都实现了用 javax.persistence.PostLoad 注释的方法,会发生什么?必须调用哪个方法以及首先调用哪个方法?它是否取决于方法的可见性(私有(private)、公共(public))?

(Hibernate 默认 session 根本不调用此类方法,我将使用 Hibernate PostLoadEventListener 实现解决方法。)

最佳答案

让我复制 Java Persistence API 2.0 FR 规范的一些部分,我相信这可能会回答您的问题。

3.5.1 生命周期回调方法

The callback methods can have public, private, protected, or package level access, but must not be static or final.

3.5.4 实体生命周期事件的多种生命周期回调方法

If multiple classes in an inheritance hierarchy—entity classes and/or mapped superclasses—define entity listeners, the listeners defined for a superclass are invoked before the listeners defined for its subclasses in this order.

(...)

If a lifecycle callback method for the same lifecycle event is also specified on the entity class and/or one or more of its entity or mapped superclasses, the callback methods on the entity class and/or superclasses are invoked after the other lifecycle callback methods, most general superclass first.

下面的部分提供了一个可能会解决您的问题的非常详细的示例:

3.5.5 示例

There are several entity classes 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 a PostPersist event occurs on an instance of Cat, the following methods are called in order:
- postPersistPetListenerMethod
- postPersistCatListenerMethod
- postPersistCatListener2Method
- postPersistAnimal

希望对您有所帮助!

关于Java EE 持久性。嵌套@PostLoad。 supercalss中的PostLoad回调方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8150322/

相关文章:

java - Java正则表达式中的匹配字符

java - @EnableAspectJAutoProxy 不起作用

java - redhat机器安装j2sdk 1.4.2_09

java - 这个 JPA "cached hashCode"模式有什么陷阱吗?

java - 有人可以解释一下这个 hibernate 方法的作用吗?

java - Objectify:排序查询结果 ("no matching index found"错误)

java - 从 Hibernate 切换到实现 Hibernate 的 JPA 接口(interface)

java - 如何在 AS 级别为 EJB stub 创建我自己的代理

java - 如何实现xxx.domainname.com URL模式?

java - 有状态 session bean 的消息驱动 bean 没有响应