如何在 Jpa 实体中使用 Java 继承

Pri*_*mal 2 java hibernate jpa spring-data-jpa spring-boot

我试图通过使用继承来创建 JPA 实体,我没有使用任何 JPA 多态机制来做到这一点。原因是我希望模型类是独立的,所以如果我想使用 JPA,我可以扩展相同的模型类并创建 JPA 实体并完成工作。我的问题是,这是否可以在不使用 JPA 多态机制的情况下实现,因为当我尝试处理扩展模型类后创建的 JPA 实体时,我看不到从超类继承的属性,但我可以看到新的属性如果我将新属性添加到扩展的 JPA 实体中,则在表中。

这是我的实体:

@Data
public abstract class AtricleEntity {

    protected Integer Id;
    protected String title;
    protected Integer status;
    protected String slug;
    protected Long views;
    protected BigDecimal rating;
    protected Date createdAt;
    protected Date updatedAt;
}


@Data
@Entity
@Table(name="articles_article")
@RequiredArgsConstructor
public class Article extends AtricleEntity {

    public static final String TABLE_NAME = "articles_article";

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer Id;

    private String title;
}



@Repository
public interface ArticleRepository extends JpaRepository<Article, Integer>{}
Run Code Online (Sandbox Code Playgroud)

title如果我运行它,我可以看到一个带有列的表。那是因为我已经在 中明确添加了该属性Article,但我希望在 Java 继承的帮助下其他列出现在表中。这可能吗?

Kar*_*k R 5

简单的答案是否定的。JPA 不能使用开箱即用的对象继承,原因很简单,其他子项将具有不同的列名和其他参数,甚至可能选择不保存这些列。

所以 JPA 有它自己的继承映射,对象可能必须遵循它。使用 likeMappedSuperclass可能会有所帮助。 参考: http : //www.baeldung.com/hibernate-inheritance用于休眠。