emt*_*t14 9 java inheritance hibernate 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 {
...
}
Run Code Online (Sandbox Code Playgroud)
但我一直在绊倒下面的映射错误,我真的不知道这是否可行?
JPA error
A JPA error occurred (Unable to build EntityManagerFactory): Use of @OneToMany or
@ManyToMany targeting an unmapped class: models.Report.items[models.OpsItem]
Run Code Online (Sandbox Code Playgroud)
UPDATE
我认为问题不在于抽象类,而在于@MappedSuperClass注释.看起来jpa不喜欢用@MappedSuperClass映射一对多的关系.如果我将抽象类更改为具体类,则会出现相同的错误.
如果我然后更改为@Entity注释,这似乎适用于抽象类和具体类.
使用@Entity映射抽象类似乎有点奇怪.我错过了什么?
解
在rhinds的帮助下进行管理.有两点需要注意:
1)抽象类需要使用@Entity和每个类的表的继承策略进行注释,以便子类拥有自己的表.
2)Identity Id生成在这种情况下不起作用,我不得不使用Table生成类型.
@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 {
...
}
Run Code Online (Sandbox Code Playgroud)
是的,这是可能的.您应该只在顶层抽象类上拥有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 {
...
}
Run Code Online (Sandbox Code Playgroud)
有关其使用的详细信息,请查看hibernate文档的这一部分:http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e1168
UPDATE
对不起,完全错过了每班课程的表格.Hibernate不支持每个类的表抽象对象的映射(如果所有实现都在一个SQL表中,则只能映射List,而TABLE_PER_CLASS使用"每个具体类的表"策略.
限制细节和策略如下:http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#inheritance-limitations