[英]ManyToOne FetchType.LAZY does not work. null always returned when getting the list
I am using JPA with Spring Boot.我正在使用 JPA 和 Spring 引导。 I have entities:
我有实体:
@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
}
Then in my test, I try to retrieve the book placed in the bookshelf:然后在我的测试中,我尝试检索放在书架上的书:
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);
The test fails because getBooks() always return null in this line:测试失败,因为 getBooks() 总是在此行中返回 null:
int count = persistedShelf.getBooks().size();
Test log shows only two SQL commands are executed:测试日志显示只执行了两条 SQL 命令:
Hibernate: insert into bookshelf (location, id) values (?, ?)
Hibernate: insert into book (author, bookshelf_id, title, id) values (?, ?, ?, ?)
What can be the problem?可能是什么问题?
Try also setting the inverse relationship from shelf to book:尝试设置从书架到书的反比关系:
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();
In general you are responsible for managing both sides of the relationship in JPA/Hibernate.一般来说,您负责管理 JPA/Hibernate 中关系的双方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.