我在 Spring Boot 中使用 JPA。我有实体:
@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 (?, ?, ?, ?)
可能是什么问题?
答案 0 :(得分:0)
尝试设置从书架到书的逆关系:
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 中的双方关系。