Note that there are some explanatory texts on larger screens.

plurals
  1. POJPA fetching one to many
    primarykey
    data
    text
    <p>I have the following entities: Event and Attribute. An event can have many attributes. </p> <p>The problem I am having is, I can't seem to find a query that returns the events with their attributes in a single SQL query. I could have millions of events that need to be iterated through and I don't want to lazy load them all for obvious performance reasons.</p> <p>I've tried using fetch in the query, but it returns an event for every attribute. i.e. if an event had 2 attributes it would return 2 events each with one attribute. </p> <p>What I want is one event with 2 attributes.</p> <pre><code>SELECT e FROM Event e LEFT JOIN FETCH e.attributes </code></pre> <p>If I add DISTINCT it works, but then it creates a distinct SQL query which is extremely slow over large data sets.</p> <pre><code>public class Event { @OneToMany(mappedBy = "event", cascade = CascadeType.ALL, fetch = FetchType.LAZY) public Set&lt;Attribute&gt; getAttributes(){} } public class Attribute { @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name = "event_id", nullable = false) public Event getEvent() { return event; } } </code></pre> <p><strong>Solution</strong></p> <p>I couldn't find a JPA solution. Instead, I unwrapped the EntityManager to the Hibernate session and used the criteria's result transformer as @milkplusvellocet suggested. This retrieves distinct root entities without creating a distinct SQL query.</p> <pre><code>Session session = em.unwrap(Session.class); Criteria criteria = session.createCriteria(Event.class); criteria.setFetchMode("attributes", FetchMode.JOIN); criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); </code></pre> <p>One thing to note is, I tried using HQL from the unwrapped session. I added DISTINCT to the query and set the result transformer to DISTINCT_ROOT_ENTITY similar to the criteria solution above. Doing it this way <strong>still</strong> created a distinct SQL query. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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