I have an entity (Book) with an ElementCollection for a List property (tags).
@Entity
@Table(name = "BOOK")
public class Book {
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "BOOK_TAGS", joinColumns = @JoinColumn(name = "BOOK_ID"))
@Column(name = "TAG", length = "4000")
private List<String> tags;
}
For getting a single book, I’m doing entityManager.find and for getting all the books, I’m doing criteria query. This all works. I now want to make the list of tags lazily loaded, which will prevent them from loading when I get all books (which I want) but I still want to load them when I get a particular Book.
My first attempt is to change the entityManager.find to a query. The following works:
select b from Book b left outer join fetch b.tags where b.id = :id
However, I want to do this as a CriteriaQuery as well as add the option for getting tags on the get all books query. Doing the following is not working:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Book.class);
Root<Book> b = cq.from(Book.class);
b.fetch("tags", JoinType.LEFT);
cq.select(b);
cq.where(cb.equal(b.get("id"),cb.parameter(String.class,"id"));
TypedQuery<Book> q = em.createQuery(cq);
q.setParameter(id);
return q.getSingleResult();
This is failing in that it is not a single result – its looking like N objects where N is the number of tags.
I also tried adding:
q.setHint("eclipselink.join-fetch","b.tags");
and taking out the fetch but that also doesn’t work.
I’m getting the columns added to the SQL but its like the processing of those extra columns is messing up the returned object – its either multiples or no object (for hints).
Any ideas how to turn the JOIN FETCH into a proper CriteriaQuery?
Answering my own question – join fetch is not the way to go here as that will mess up result counting – trick is to use batch fetching via QueryHints – and pre-loading the tags as well as a QueryHint.