2011-11-07 111 views
0

我是Hibernate的新手,所以我的問題可能會很愚蠢,因爲我被困住了,很樂意獲得幫助。休眠OneToMany。從數據庫加載時獲取空列表

我有兩個實體:書和標籤具有以下結構:

@Entity 
public class BookEntity{ 

@Column(nullable = false) 
private String title; 
@Column(nullable = false) 
private String author; 
private String publisher; 
private int edition; 
private int yearOfPublishing; 

@Id 
@Column(name = "isbn") 
private String isbn; 

@ElementCollection(fetch = FetchType.EAGER) 
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER) 
@JoinTable(joinColumns = { @JoinColumn(name = "isbn") }, 
      inverseJoinColumns = { @JoinColumn(name = "tagId") }) 
private List<Tag> tags; 
//getters & setters 

@Entity 
public class Tag implements Serializable { 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
private int tagId; 
private String tagValue; 
//getters & setters 

插入正常工作,這裏是HQL查詢:

insert into PUBLIC.BookEntity 
(author, edition, publisher, title, yearOfPublishing, isbn) 
values (?, ?, ?, ?, ?, ?) 

insert into PUBLIC.Tag 
(tagId, tagValue) 
values (null, ?) 

選擇查詢看起來不錯還有:

select 
     bookentity0_.isbn as isbn35_1_, 
     bookentity0_.author as author35_1_, 
     bookentity0_.edition as edition35_1_, 
     bookentity0_.publisher as publisher35_1_, 
     bookentity0_.title as title35_1_, 
     bookentity0_.yearOfPublishing as yearOfPu6_35_1_, 
     tags1_.isbn as isbn35_3_, 
     tag2_.tagId as tagId3_, 
     tag2_.tagId as tagId36_0_, 
     tag2_.tagValue as tagValue36_0_ 
    from 
     PUBLIC.BookEntity bookentity0_ 
    left outer join 
     PUBLIC.BookEntity_Tag tags1_ 
      on bookentity0_.isbn=tags1_.isbn 
    left outer join 
     PUBLIC.Tag tag2_ 
      on tags1_.tagId=tag2_.tagId 
    where 
     bookentity0_.isbn=? 

但是,當我從數據庫中加載BookEntity我得到正確的對象與標籤的空列表。 從數據庫加載對象:

public T read(PK id) { 
    LOG.debug("Reading by id={}", id.toString()); 
    return (T)getSession().get(type, id); 
} 

其中T是BookEntity,類型爲類和PK是字符串。

我在做什麼錯了? 在此先感謝。

+0

插入到'BookEntity_Tag'連接表中的位置在哪裏? – millhouse

回答

1

首先選擇isbn作爲主鍵不是最受啓發的想法。如果用戶輸入錯誤並輸入錯誤的isbn會怎麼樣?

其次,在我看來,你試圖映射從書到標籤的多對多關係。或者也許是一對多?

對於多對多使用:

@ManyToMany 
@JoinTable(name = "book_tag", 
    joinColumns = {@JoinColumn(name = "isbn")}, 
    inverseJoinColumns = {@JoinColumn(name = "tag_id")} 
) 

對一對多用途:

@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER) 
@JoinColumn(name = "isbn", nullable = false) 

但你最好用book_id替換ISBN。

+0

謝謝,這工作!關於isbn - 客戶端代碼只會通過Builder驗證isbn代碼來創建圖書,因此它不會讓用戶堅持錯誤的數據。當isbn是pk時,更易於kepp數據完整性。 – Grook