编程语言
首页 > 编程语言> > java-未在父级上调用Jpa prepersist回调

java-未在父级上调用Jpa prepersist回调

作者:互联网

我的密码

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class SiteMessage implements Identifiable{
    @PrePersist
    public void onCreate1(){
        System.out.println("Executed onCreate1");
    }
}

@Entity
@Table(name = "feedback")
public class Feedback extends SiteMessage {
    @PrePersist
    public void onCreate2(){
        System.out.println("Executed onCreate2");
    }
}

当我保存反馈实体时,我希望我会看到:执行onCreate1和执行onCreate2,但是我只看到了执行oncreate2

我使用eclipselink v2.5.2

解决方法:

《精通Java持久性API的书》记录了以下内容:

Inheriting Callback Methods

Callback methods may occur on any entity or mapped superclass, be it
abstract or concrete. The rule is fairly simple. It is that every
callback method for a given event type will be invoked in the order
according to its place in the hierarchy, most general classes first.

Thus, if in our Employee hierarchy that we saw in Figure 10-10 the
Employee class contains a PrePersist callback method named
checkName(), and FullTimeEmployee also contains a PrePersist callback
method named verifyPension(), when the PrePersist event occurs, the
checkName() method will get invoked, followed by the verifyPension()
method.

因此,如果原始代码中的所有其他内容都正确,那么您应该期望按该顺序看到onCreateOne()和onCreateTwo().

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class SiteMessage implements Identifiable{
    @PrePersist
    public void onCreateOne(){
        System.out.println("Executed onCreate1"); //executes first
    }
}

@Entity
@Table(name = "feedback")
public class Feedback extends SiteMessage {
    @PrePersist
    public void onCreateTwo(){
        System.out.println("Executed onCreate2"); //executes second
    }
}

它会继续注意以下内容,因此您应该能够完全根据需要进行设置.

We could also have a method on the CompanyEmployee mapped superclass
that we want to apply to all the entities that subclassed it. If we
add a PrePersist method named checkVacation() that verifies that the
vacation carryover is less than a certain amount, it will be executed
after checkName() and before verifyPension(). It gets more interesting
if we define a checkVacation() method on the PartTimeEmployee class
because part-time employees don’t get as much vacation. Annotating the
overridden method with PrePersist would cause the
PartTimeEmployee.checkVacation() method to be invoked instead of the
one in CompanyEmployee

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class SiteMessage implements Identifiable{
    @PrePersist
    public void onCreate(){
        System.out.println("Executed onCreate1"); //will not execute
    }
}

@Entity
@Table(name = "feedback")
public class Feedback extends SiteMessage {
    @PrePersist
    public void onCreate(){
        System.out.println("Executed onCreate2"); //will execute
    }
}

标签:java,jpa,eclipselink
来源: https://codeday.me/bug/20191013/1911191.html