急切加载所有相关对象

时间:2017-03-25 18:37:04

标签: java hibernate jpa eager

我有两个实体:

Book

@Entity
public class Book {
    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "library_id")
    private Library library;
    // Getters and setters
}

Library

@Entity
public class Library {
    @Id
    private Long id;

    @OneToMany(mappedBy = "library", fetch = FetchType.EAGER)
    private List<Book> books;
    // Getters and setters
}

我想要做的是热切地获取给定查询库的所有书籍:

Library library = em.find(Library.class, 1L);
System.out.println(library.getBooks());

但它给了我null。如何获取所有链接书籍的列表?我搜索并尝试了S.O.的许多解决方案。但都没有效果。

P.S。 - 我可以向您保证表格中存在链接数据。

2 个答案:

答案 0 :(得分:0)

问题出在@JoinColumn(name = "library_id"),因为您没有library_id列,而是将其更改为@JoinColumn(name = "id"),否则另一个选项是更改字段{{1} } idlibrary_id内的Library

您似乎没有使用表列名称映射Entity类(因为它们具有不同的名称),您需要使用@Column映射它们,如下所示:

    @Entity
    public class Book {
        @Id
        @Column(name="book_id")
        private Long id;

        @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "library_id")
        private Library library;
        // Getters and setters
    }



    @Entity
    public class Library {
       @Id
       @Column(name="library_id")
        private Long id;

        @OneToMany(mappedBy = "library", fetch = FetchType.EAGER)
        private List<Book> books;
        // Getters and setters
   }

答案 1 :(得分:0)

事实证明,对象是从缓存而不是数据库中查询的,并且它不是更新后的副本。当我在查询之前尝试清理缓存时,它起作用了:

em.clear();

我想而不是清除整个上下文,我只是分离一个对象并再次查询。

em.getTransaction().begin();

Library library = new Library(1L, "Central library");
em.persist(library);

em.persist(new Book(1L, "Harry potter", "123-123-123-123", 1000, library));

em.getTransaction().commit();
em.detach(library);   // This did the trick

library = em.find(Library.class, 1L);
System.out.println(library.getBooks());

出于某种原因,我希望它没有这个黑客。我仍然愿意接受更好的解决方案。