简体   繁体   中英

ManyToOne FetchType.LAZY does not work. null always returned when getting the list

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM