2011-03-23 53 views
0

我正在嘗試使用hibernate批註實現我的模型。我有3個班,圖片,人物和標籤。標籤是由4個字段,id,personId,imageId和createdDate組成的表。人有田姓名,身份證,出生日期,等我的形象類定義如下:Hibernate批註集合

@Entity 
@Table(name="Image") 
public class Image { 
    private Integer imageId; 
    private Set<Person> persons = new HashSet<Person>(); 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "ID") 
    public Integer getImageId() { 
     return imageId; 
    } 

    public void setImageId(Integer imageId) { 
     this.imageId = imageId; 
    } 

    @ManyToMany 
    @JoinTable(name="Tags", 
       joinColumns = {@JoinColumn(name="imageId", nullable=false)}, 
       inverseJoinColumns = {@JoinColumn(name="personId", nullable=false)}) 
    public Set<Person> getPersons() { 
     return persons; 
    } 

    public void setPersons(Set<Person> persons) { 
     this.persons = persons; 
    } 

如果我卸下getPersons()方法,我可以使用類,添加和刪除記錄的註釋。我想要使​​用圖像獲取所有標籤,並且正在嘗試使用一組圖像。我不斷收到以下錯誤:

org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: com.exmaple.persons, no session or session was closed 

有人可以幫助我,讓我知道我在做什麼錯嗎?

謝謝

回答

5

此錯誤消息 - 這實際上已經無關,與你的關聯映射策略或註釋 - 意味着你試圖訪問你的域對象之一後Session是一個延遲加載集合關閉。

的解決方法是禁用延遲加載此集合,明確前Session被關閉(例如,通過調用foo.getBars().size()),或在確認Session保持打開,直到它不再需要加載的集合。

如果你不確定什麼是懶惰加載,here is the section in the Hibernate manual

+0

我要去接受這個答案。我很感激幫助。我仍然在閱讀春季文檔中的第10章和第13章。我會在有機會時發佈更新。 – blong824 2011-03-28 16:14:13

0

感謝您的迴應馬特。我現在很困惑。我的查詢檢索圖像看起來是這樣的:

public Image findByImageId(Integer imageId) { 
    @SuppressWarnings("unchecked") 
    List<Image> images = hibernateTemplate.find(
      "from Image where imageId=?", imageId); 
    return (Image)images.get(0); 
} 

我認爲我可以調用一個HQL查詢,如果我的映射都是正確的,將帶回相關數據。

我在這個鏈接hibernate mappings看下面這個例子:

2.2.5.3.1.3. Unidirectional with join table 
A unidirectional one to many with join table is much preferred. This association is described through an @JoinTable. 

@Entity 
public class Trainer { 
    @OneToMany 
    @JoinTable(
      name="TrainedMonkeys", 
      joinColumns = @JoinColumn(name="trainer_id"), 
      inverseJoinColumns = @JoinColumn(name="monkey_id") 
    ) 
    public Set<Monkey> getTrainedMonkeys() { 
    ... 
} 

@Entity 
public class Monkey { 
    ... //no bidir 
}   Trainer describes a unidirectional relationship with Monkey using the join table TrainedMonkeys, with a foreign key trainer_id to Trainer (joinColumns) and a foreign key monkey_id to Monkey (inversejoinColumns). 
+0

有沒有人對我的跟進問題有任何其他意見?謝謝 – blong824 2011-03-24 18:27:53

+0

我不知道我是否明白你在這裏問的是什麼,但是你的查詢返回第一個'Image'實例實際上會返回對象 - 但是Hibernate延遲加載'Image.trainers'集合,消息是指。這是您在關閉會話之前必須加載的集合,或者標記爲非延遲加載。 – 2011-03-25 13:41:53

+0

我認爲這是我感到困惑的地方。所以我的查詢抓取圖像對象,它具有一組延遲加載的。所以當我要求一個特定的圖像對象時,它基本上是一個空集。我相信因爲我使用hibernateTemplate來處理會話。所以,當我做一個hibernate.find(「來自Image ...」)時,我必須對人物對象進行另一個查找並填充該集合? – blong824 2011-03-25 14:28:20