2012-03-26 53 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