做一個以前保存的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)
您可能需要顯式調用'getAuthors()'在本書中,你嘗試打印之前。 –
試過了,沒有工作:( – user1882491
見JPA生成的查詢,並確保兒童查詢被解僱,你在DB有子記錄。希望你已經嘗試了這種選擇,但一切在這裏看起來很不錯。 –