JPA @pre和@post回调未调用



我正在使用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;
    ...
}

最新更新