简体   繁体   English

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

[英]How to use Java inheritance in Jpa Entities

I'm trying to create JPA entities by using inheritance , I am not using any JPA polymorphic mechanism to do this.我试图通过使用继承来创建 JPA 实体,我没有使用任何 JPA 多态机制来做到这一点。 The reason is I want model classes to be independent, so if I want to use JPA I can extend the same model classes and create JPA entities and get the job done.原因是我希望模型类是独立的,所以如果我想使用 JPA,我可以扩展相同的模型类并创建 JPA 实体并完成工作。 My question is, is this possible to achieve without using JPA polymorphic mechanism, because when I try to deal with the JPA entities created after extending the model classes I don't see the properties that are inherited from super class but I can see new properties in the table if I add new properties in to the extended JPA entity.我的问题是,这是否可以在不使用 JPA 多态机制的情况下实现,因为当我尝试处理扩展模型类后创建的 JPA 实体时,我看不到从超类继承的属性,但我可以看到新的属性如果我将新属性添加到扩展的 JPA 实体中,则在表中。

Here are my entities:这是我的实体:

@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>{}

I can see a table with a column title created if i run this.如果我运行它,我可以看到一个带有列title的表格。 that's because I've explicitly added that property in Article , but i want other columns to appear in the table with the help of java inheritance.那是因为我已经在Article明确添加了该属性,但是我希望在 Java 继承的帮助下其他列出现在表中。 is this possible?这可能吗?

Simple answer is NO .简单的答案是否定的 JPA cannot use object's inheritance out of the box coz of the simple reason that other children will have different column names and other parameters and might choose not even to save these columns. JPA 不能使用开箱即用的对象继承,原因很简单,其他子项将具有不同的列名和其他参数,甚至可能选择不保存这些列。

So JPA has it's own inheritance mappings which an object might have to follow.所以 JPA 有它自己的继承映射,对象可能必须遵循它。 Usage like MappedSuperclass might help.MappedSuperclass这样的MappedSuperclass可能会有所帮助。 Reference : http://www.baeldung.com/hibernate-inheritance for hibernate.参考: http : //www.baeldung.com/hibernate-inheritance用于休眠。

@MappedSuperclass annotation put on your super class should help.放在超类上的@MappedSuperclass注释应该会有所帮助。 https://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html https://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM