java - 如何用jpa映射抽象集合?

标签 java hibernate inheritance jpa playframework

我正在尝试找出是否有可能让 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映射一个抽象类似乎有点奇怪。 我错过了什么吗?

解决方案

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

1) 抽象类需要注解@Entity和每类表的继承策略,让子类有自己的表。

2) Identity 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 {
...
}

最佳答案

是的,这是可能的。您应该只在顶层抽象类上有 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


更新

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

此处限制和策略的详细信息:http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#inheritance-limitations

关于java - 如何用jpa映射抽象集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9873547/

相关文章:

java - hibernate :saveorupdate() 不更新对象

java - 在 hibernate 中更新父对象时多对多关系出现问题?

c++ - 覆盖返回基类型的函数

java - 不扩展 java.lang.Object 的类

java - 无法写入核心转储。核心转储已被禁用。要启用核心转储,请在再次启动 Java 之前尝试 "ulimit -c unlimited"

java - 如何使用 GZIPInputStream 修复 EOF 读取错误

java - hibernate 连接错误无法获取数据

Java如何指定一个采用父类(super class)的子类的方法

java - 多个集合上的迭代器

java - 无限 While 循环