0

I have two entities:

Book:

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

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

and Library:

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

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

What I want to do is eagerly fetch all the books for a given queried library:

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

But it gives me null. How do I get list of all the linked books? I have searched and tried many solutions from S.O. but none works.

P.S. - I can assure you that there is linked data present in the tables.

4

2 回答 2

0

问题@JoinColumn(name = "library_id")在于您没有library_id列,而是将其更改为@JoinColumn(name = "id"),否则另一个选项是将字段更改idlibrary_id内部Library类。

似乎您没有使用表列名称映射实体类(因为它们具有不同的名称),您需要使用它来映射它们@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
   }
于 2017-03-25T18:45:12.360 回答
0

It turns out the object was being queried from cache rather than database and it wasn't an updated copy. As I tried cleaning up the cache before querying, it worked:

em.clear();

I figured instead of clearing the whole context, I'll just detach one object and query it again.

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());

For some reason I wanted it worked without this hack. I am still open to better solutions.

于 2017-03-25T19:12:21.310 回答