![](/img/trans.png)
[英]Why am I getting a LazyInitializationException when using FetchType.LAZY on one Set, but not on the other?
[英]ManyToOne FetchType.LAZY does not work. null always returned when getting the list
我正在使用 JPA 和 Spring 引导。 我有实体:
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false, unique = true)
private String title;
@Column(nullable = false)
private String author;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "bookshelf_id", referencedColumnName = "id", nullable = true)
private Bookshelf bookshelf;
// getter & setter
}
@Entity
public class Bookshelf {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String location;
@OneToMany(mappedBy = "bookshelf", fetch = FetchType.LAZY)
private List<Book> books;
// getter & setter
}
然后在我的测试中,我尝试检索放在书架上的书:
Bookshelf shelf = new Bookshelf("room A");
Book book = new Book("a book", "chris");
book.setBookshelf(shelf);;
entityManager.persist(book);
entityManager.persist(shelf);
entityManager.flush();
Bookshelf persistedShelf = bookshelfRepository.findById(shelf.getId()).get();
Book persistedBook = bookRepository.findById(book.getId()).get();
book = null;
shelf = null;
shelf = persistedBook.getBookshelf();
int count = persistedShelf.getBooks().size();
assertEquals(1, count);
测试失败,因为 getBooks() 总是在此行中返回 null:
int count = persistedShelf.getBooks().size();
测试日志显示只执行了两条 SQL 命令:
Hibernate: insert into bookshelf (location, id) values (?, ?)
Hibernate: insert into book (author, bookshelf_id, title, id) values (?, ?, ?, ?)
可能是什么问题?
尝试设置从书架到书的反比关系:
Bookshelf shelf = new Bookshelf("room A");
Book book = new Book("a book", "chris");
book.setBookshelf(shelf);
// new code here:
List<Book> books = new ArrayList<>();
books.add(book);
shelf.setBooks(books);
entityManager.persist(book);
entityManager.persist(shelf);
entityManager.flush();
一般来说,您负责管理 JPA/Hibernate 中关系的双方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.