2012-03-26 51 views
9

我想解决如果有可能让JPA坚持具体实现的抽象集合。如何用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] 

UPDATE

我不认为这个问题是与抽象类,但在@MappedSuperclass注解。 它看起来像jpa不喜欢与@MappedSuperClass映射一对多关系。 如果我将抽象类更改为具体的类,则具有相同的错误。

如果我然后更改为@Entity注释,这似乎与抽象和具体类一起工作。

这与用@Entity绘制抽象类似乎有点奇怪。 我我错过了什么?

SOLUTION

管理与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 { 
... 
} 

回答

6

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

尝试将其更改为这样的事情:

@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 { 
... 
} 

检查其使用方式与休眠文档的这一部分:http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e1168


UPDATE

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

局限性和策略的详细信息这里:http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#inheritance-limitations

+0

我试过了,但仍然出现这个错误。当它涉及映射项目集时,似乎会感到困惑。我也尝试指定映射的实体,但仍得到相同的错误消息。 – emt14 2012-03-26 14:36:17

+0

看到我更新的答案 – rhinds 2012-03-26 15:09:46

+0

Humm,所以基本上在抽象类和几个具有自己的表的具体实现上有一对多的关系是不可能的? – emt14 2012-03-26 15:33:30