【问题标题】:Spring-Data Jpa Inheritance: Keeping Entity Id's in Children EntitySpring-Data Jpa 继承:将实体 ID 保留在子实体中
【发布时间】:2019-04-17 14:09:32
【问题描述】:

我正在处理一些具有树状结构的实体,它们变得越来越复杂,因此我决定为其创建一个抽象类,以便代码更易于维护:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class TreeStructure<T extends TreeStructure>
{
    @ManyToOne
    protected  T parent;

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    protected Set<T> children = new HashSet<>();
    //...

然后我有两个扩展它的实体:

@Entity(name = "TreeStructureOne")
public class TreeStructureOne extends TreeStructure<TreeStructureOne>
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonProperty("TreeStructureOne_id")
    private long id;

我基本上希望数据库完全不知道这个TreeStructure 抽象并将所有字段保存在每个实体表中,并希望InheritanceType.TABLE_PER_CLASS 处理它。但似乎我至少需要在TreeStructure 实体中定义Id,否则我会得到:

Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: TreeStructure

我不想将ID 添加到抽象类中,因为这会在数据库中生成三个名为:HT_TREE_STRUCTUREHT_TREE_STRUCTURE_ONEHT_TREE_STRUCTURE_TWO 的表,每个表都有一个字段ID

有什么解决办法吗?

【问题讨论】:

  • 您是否尝试将@MappedSuperclass 用于TreeStructure 类而不是@Entity@Inheritance@MappedSuperclass 没有自己的表,也不是实体。 docs.oracle.com/javaee/5/api/javax/persistence/…
  • 不,我不知道!它通过了我所做的所有测试,这正是我想要的。非常感谢!
  • 太棒了!我只是把它作为一个答案

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


【解决方案1】:

因为TreeStructure 不是@Entity,所以只能使用@MappedSuperclass

@MappedSuperclass
public abstract class TreeStructure<T extends TreeStructure> {

而不是 @Entity@Inheritance 用于父类。

您可以在Oracle JEE API documentation 中找到@MappedSuperclass

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2019-09-30
    • 1970-01-01
    • 2018-08-03
    • 2015-02-17
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多