2014-01-15 87 views
1

做一個以前保存的1對多的實體的查找。授權是:JPA一對多集合返回空

Book.java:

@Entity 
@Table(name = "Book") 
public class Book { 

    @Id 
    @GeneratedValue 
    @Column(name = "id") 
    private Long id; 

    @OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="book", orphanRemoval=true) 
    private Collection<Author> authors; 

    public Collection<Author> getAuthors() { 
     return authors; 
    } 
     ... 

     @Override 
    public String toString() { 
     return "Book [id=" + id + ", authors=" + authors + ", title=" + title 
       + ", isbn=" + isbn + "]"; 
    } 
} 

Author.java:

@Entity 
@Table(name = "Authors") 
public class Author { 

    @Id 
    @GeneratedValue 
    @Column(name="id") 
    private Long id; 

    @ManyToOne(fetch=FetchType.LAZY) 
    @JoinColumn(name="book_id") 
    private Book book; 

     ... 

    @Override 
    public String toString() { 
     return "Author [id=" + id + ", book=" + book + ", firstName=" 
      + firstName + ", lastName=" + lastName + "]"; 
    } 
} 

忽略數據模型的可疑基數,查找碼是

long bookID = 10; // saved entity ID 
entityManager.getTransaction().begin(); 
Book savedBook = entityManager.find(Book.class, bookID); 
System.out.println("Book " + savedBook); 
entityManager.getTransaction().commit(); 

其給出輸出

Book Book [id=10, authors=[], title=Treasure Island, isbn=123456] 

任何想法,爲什麼作者是空的?


Retrieving 11... 

Exception in thread "main" java.lang.StackOverflowError 
    at java.lang.Long.toString(Long.java:240) 
    at java.lang.Long.toString(Long.java:100) 
    at java.lang.String.valueOf(String.java:2946) 
    at java.lang.Long.toString(Long.java:733) 
    at java.lang.String.valueOf(String.java:2827) 
    at java.lang.StringBuilder.append(StringBuilder.java:115) 
    at org.hibstore.domain.Book.toString(Book.java:64) 
    at java.lang.String.valueOf(String.java:2827) 
    at java.lang.StringBuilder.append(StringBuilder.java:115) 
    at org.hibstore.domain.Author.toString(Author.java:67) 
    at java.lang.String.valueOf(String.java:2827) 
    at java.lang.StringBuilder.append(StringBuilder.java:115) 
    at java.util.AbstractCollection.toString(AbstractCollection.java:422) 
    at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:501) 
    at java.lang.String.valueOf(String.java:2827) 
    at java.lang.StringBuilder.append(StringBuilder.java:115) 
    at org.hibstore.domain.Book.toString(Book.java:64) 
    at java.lang.String.valueOf(String.java:2827) 
+0

您可能需要顯式調用'getAuthors()'在本書中,你嘗試打印之前。 –

+0

試過了,沒有工作:( – user1882491

+0

見JPA生成的查詢,並確保兒童查詢被解僱,你在DB有子記錄。希望你已經嘗試了這種選擇,但一切在這裏看起來很不錯。 –

回答

2

同時插入記錄的問題可能是。 您需要家長設置爲兒童和增加孩子家長喜歡book.addAuthor(author);author.setBook(book)爲孩子在這裏開車的關係。

+0

我不明白這是如何。你能告訴我在這種情況下發生了什麼? – cst1992

1

另一種解決這個問題本來是@ManyToOne的實體作者>本書字段映射設置爲@ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.PERSIST)

+0

試過這個,沒有工作,謝謝你的回答,雖然:) – user1882491