简体   繁体   English

Spring-Data Jpa继承:在子实体中保留实体ID

[英]Spring-Data Jpa Inheritance: Keeping Entity Id's in Children Entity

I'm dealing with a couple of Entities with Tree like structures that were getting more complicated so I decided to create an abstract class for it so code was a bit more mainainable: 我正在处理几个使用树状结构的实体,这些实体变得越来越复杂,所以我决定为它创建一个抽象类,所以代码更加可维护:

@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<>();
    //...

Then I have two Entities which extend it: 然后我有两个扩展它的实体:

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

And I basically want the database to be completely unaware of this TreeStructure abstraction and save all of the fields in each Entities tableand expected InheritanceType.TABLE_PER_CLASS to deal with that. 我基本上希望数据库完全不知道这个TreeStructure抽象,并保存每个Entities表中的所有字段,并期望InheritanceType.TABLE_PER_CLASS来处理它。 But it seems I need to define the Id in the TreeStructure Entity at least or I get: 但似乎我需要至少在TreeStructure实体中定义Id ,或者我得到:

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

And I don't want to add an ID into the abstract class since this makes three tables in the database called: HT_TREE_STRUCTURE , HT_TREE_STRUCTURE_ONE and HT_TREE_STRUCTURE_TWO with one field ID each one. 我不想在抽象类中添加ID ,因为这会在数据库中生成三个表: HT_TREE_STRUCTUREHT_TREE_STRUCTURE_ONEHT_TREE_STRUCTURE_TWO ,每个HT_TREE_STRUCTURE_TWO都有一个字段ID

Is there any solution to that? 那有什么解决方案吗?

Since TreeStructure is not an @Entity use only @MappedSuperclass 由于TreeStructure不是@Entity只使用@MappedSuperclass

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

instead of @Entity and @Inheritance for the parent class. 而不是父类的@Entity@Inheritance

You can find @MappedSuperclass in the Oracle JEE API documentation . 您可以在Oracle JEE API文档中找到@MappedSuperclass

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

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