问题
My code
@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");
}
}
When i save Feedback entity i expect that i will see: Executed onCreate1 and Executed onCreate2, but i've seen only Executed onCreate2
I use eclipselink v2.5.2
回答1:
The Book Mastering the Java persistence API notes the following:
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.
Therefore if everything else in your original code was correct you should expect to see both onCreateOne() and onCreateTwo() called and in that order.
@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
}
}
It goes on to note the following so you should be able to set things up exactly as required.
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
}
}
来源:https://stackoverflow.com/questions/26060940/jpa-prepersist-callback-not-called-on-parent