查找以前保存的1对多实体。标题是:
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 :(得分:2)
插入记录时可能出现问题。
您需要将父级设置为子级,并将子级添加到父级,如book.addAuthor(author);
和author.setBook(book)
,因为孩子正在这里推动这种关系。
答案 1 :(得分:1)
此问题的另一个解决方案可能是设置实体作者&gt;将@ManyToOne的书籍字段映射到@ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.PERSIST)