小编典典

如何使用jpa映射抽象集合?

hibernate

我正在尝试确定是否有可能让JPA保留具有具体实现的抽象集合。

到目前为止,我的代码如下所示:

@Entity
public class Report extends Model {

    @OneToMany(mappedBy = "report",fetch=FetchType.EAGER)
    public Set<Item> items;
}

@MappedSuperclass
public abstract class OpsItem extends Model {

    @ManyToOne
    public RetailOpsBranch report;
}


@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class AItem extends OpsItem {
...
}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class BItem extends OpsItem {
...
}

但是我一直在绊脚石下面的映射错误,我真的不知道这是否可行?

JPA error
A JPA error occurred (Unable to build EntityManagerFactory): Use of @OneToMany or
@ManyToMany targeting an unmapped class: models.Report.items[models.OpsItem]

更新

我不认为问题出在抽象类上,而是 @MappedSuperClass 批注。看起来jpa不喜欢使用 @MappedSuperClass
映射一对多关系。如果我将抽象类更改为具体类,则会遇到相同的错误。

如果我然后更改为 @Entity 批注,这似乎适用于抽象类和具体类。

@Entity 映射抽象类似乎有点奇怪。我想念什么吗?

在rinds的帮助下设法解决了这个问题。需要注意两点:

1)抽象类需要使用@Entity和每个类的表继承策略进行注释,以使子类具有自己的表。

2)身份ID生成在这种情况下将不起作用,我不得不使用表生成类型。

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class OpsItem extends GenericModel {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    public Long id;

    public String          branchCode;

    @ManyToOne
    public Report report;
}

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class AItem extends OpsItem {
...
}

阅读 357

收藏
2020-06-20

共1个答案

小编典典

是的,有可能。您应该只在顶部的抽象类上拥有MappedSuperClass(它本身不会持久化),并在实现类上添加Entity批注。

尝试将其更改为如下所示:

@MappedSuperclass
public abstract class OpsItem extends Model {

    @ManyToOne
    public RetailOpsBranch report;
}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class AItem extends OpsItem {
...
}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class BItem extends OpsItem {
...
}

检查hibernate文档的此部分以获取有关其使用的详细信息:http
:
//docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e1168


更新

抱歉,完全错过了每班位的餐桌。Hibernate不支持为每个类的表映射抽象对象(如果所有实现都在单个SQL表中,则只能映射List,并且TABLE_PER_CLASS使用“每个具体类的表”策略。

有关限制和策略的详细信息,请参见:http :
//docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#inheritance-
limitations

2020-06-20