Issue
I am using JPA with Spring Boot. 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:
int count = persistedShelf.getBooks().size();
Test log shows only two SQL commands are executed:
Hibernate: insert into bookshelf (location, id) values (?, ?)
Hibernate: insert into book (author, bookshelf_id, title, id) values (?, ?, ?, ?)
What can be the problem?
Solution
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.
Answered By - Tim Biegeleisen