Note that there are some explanatory texts on larger screens.

plurals
  1. POJPA EclipseLink @ElementCollection join fetch via CriteriaQuery
    text
    copied!<p>I have an entity (Book) with an ElementCollection for a List property (tags).</p> <pre><code>@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&lt;String&gt; tags; } </code></pre> <p>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.</p> <p>My first attempt is to change the entityManager.find to a query. The following works:</p> <pre><code>select b from Book b left outer join fetch b.tags where b.id = :id </code></pre> <p>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:</p> <pre><code>CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Book.class); Root&lt;Book&gt; 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&lt;Book&gt; q = em.createQuery(cq); q.setParameter(id); return q.getSingleResult(); </code></pre> <p>This is failing in that it is not a single result - its looking like N objects where N is the number of tags.</p> <p>I also tried adding:</p> <pre><code>q.setHint("eclipselink.join-fetch","b.tags"); </code></pre> <p>and taking out the fetch but that also doesn't work.</p> <p>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).</p> <p>Any ideas how to turn the JOIN FETCH into a proper CriteriaQuery?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload