Search code examples
javajpajpql

How to use LAZY loading for OneToMany Unidirection in JPA 2.0?


Is it possible to use LAZY loding in OneToMany unidirection mapping? In my example, BookShelf have a list of Book as LAZY loading.

I need to retrieve bookList by BookShelf's ID, again. I would like to know possible way selet many from OneToMany unidirection mapping.

Book.java

@Entity
public class Book implements Serializable {
    @Id
    private String id;
    ....
}

BookShelf.java

@Entity
public class BookShelf implements Serializable {
    @Id
    private String id;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "BOOK_SHELF_ID", referencedColumnName = "ID")
    private List<Book> bookList;
}

I would like to find book list by BookShelf using JPQL, not native query.


Solution

  • Use JOIN table strategy. As below;

    Query q =  em.createQuery("SELECT bs.bookList FROM BookShelf bs LEFT JOIN FETCH bs.bookList WHERE bs.id = :bookShelfId");
    q.setParameter("bookShelfId", bookShelfId);
    List<Book>  result = q.getResultList();