我正在使用Spring Boot 2与Hibernate上的JPA一起使用。
我必须制作一些实体才能具有特殊的审核功能。我可以简单地使用实体类中的@PrePersist
/@PostPersist
回调来实现它。
我想将此回调放在基类中。但是,如果此基类是没有@Entity
注释的简单Java类,则未调用回调。如果我也将@Entity
注释也放在基类上,那么我有一个错误Table 'my_base_class_entity' doesn't exist
。
这有效:
@Entity
@Table(name = "document")
public class JpaDocument {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
...
@PrePersist
public void prePersist(){
logger.debug("PrePersist started");
}
}
这不是(未调用回调函数(
public abstract class SpecialEntity {
@PrePersist
public void prePersist(){
logger.debug("PrePersist started");
}
}
@Entity
@Table(name = "document")
public class JpaDocument extends SpecialEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
...
}
可能我应该在我的SpecialEntity
类中添加@Entity
注释,但它迫使我添加主键,而我不想要的,因为它在儿童实体之间并不总是相同的。除了此SpecialEntity
没有数据库关系,它不是真实的实体。
解决方案非常简单。感谢@jb_nizet评论。而不是@Entity
注释@MappedSuperclass
注释已添加到基类中,因此可以正常工作。
@MappedSuperclass
public class SpecialEntity {
@PrePersist
public void prePersist(){
logger.debug("PrePersist started");
}
}
@Entity
@Table(name = "document")
public class JpaDocument extends SpecialEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
...
}