簡體   English   中英

ManyToOne FetchType.LAZY 不起作用。 null 獲取列表時總是返回

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM