我正在尝试使用继承创建 JPA 实体,我没有使用任何 JPA 多态机制来执行此操作。原因是我希望模型类是独立的,所以如果我想使用 JPA,我可以扩展相同的模型类并创建 JPA 实体并完成工作。我的问题是,这是否可以在不使用 JPA 多态机制的情况下实现,因为当我尝试处理在扩展模型类后创建的 JPA 实体时,我看不到从父类(super class)继承的属性,但我可以看到新属性如果我将新属性添加到扩展的 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 继承的帮助下出现在表中。这可能吗?
最佳答案
简单的回答是否。 JPA 不能开箱即用地使用对象的继承,原因很简单,其他子项将具有不同的列名和其他参数,甚至可能选择不保存这些列。
所以 JPA 有它自己的继承映射,对象可能必须遵循这些映射。像 MappedSuperclass
这样的用法可能会有帮助。
引用: http://www.baeldung.com/hibernate-inheritance用于 hibernate 。
关于java - 如何在 Jpa 实体中使用 Java 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51098010/