【问题标题】:How to use Java inheritance in Jpa Entities如何在 Jpa 实体中使用 Java 继承
【发布时间】:2018-06-29 09:00:00
【问题描述】:

我正在尝试通过使用继承来创建 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>{}

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

【问题讨论】:

    标签: java hibernate spring-boot jpa spring-data-jpa


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      @MappedSuperclass 注释放在你的超类上应该会有所帮助。 https://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html

      【讨论】:

      • 但我不建议在子类中复制字段。改为在超类中提供基字段的 getter 和 setter。
      猜你喜欢
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 2013-12-04
      • 2019-04-17
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多