Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>OK. So you want to load dealers with their makes, and you only want the dealers having an ID greater than a given ID.</p> <p>First of all, you could just load dealers. The list of their makes would automatically be loaded by Hibernate when you would call <code>getDealerMakes()</code>:</p> <pre><code>Criteria c = session.createCriteria(Dealer.class); c.add(Restrictions.gt("dealerId", dealerId)); // let's say delerId = 6 List&lt;Dealer&gt; dealers = c.list(); // execute SQL query select d.* from dealer d where d.dealer_id &gt; 6 for (Dealer dealer : dealers) { Set&lt;Make&gt; make = dealer.getDealerMakes() // execute SQL query select m.* from make m where m.dealer_id = &lt;theIdOfTheCurrentDealer&gt; } </code></pre> <p>This has the disadvantage of executing N + 1 queries.</p> <p>So if you want to load the dealers and their makes in a single query, you need to set a fetch mode so that the makes are loaded. Note that since the join uses the association that you defined between Dealer and Make, you don't need to tell Hibernate that the ID of the dealer table must be equal to the dealer_id of the make table: Hibernate already knows that thanks to the JoinColumn annotation that you put on the association. The query is thus the following:</p> <pre><code>Criteria c = session.createCriteria(Dealer.class); c.add(Restrictions.gt("dealerId", dealerId)); // this tells Hibernate that the makes must be fetched from the database // you must use the name of the annotated field in the Java class: dealerMakes c.setFetchMode("dealerMakes", FetchMode.JOIN); // Hibernate will return instances of Dealer, but it will return the same instance several times // once per make the dealer has. To avoid this, you must use a distinct root entity transformer criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List&lt;Delaer&gt; dealers = c.list(); // executes the SQL query: // select d.*, m.* from dealer d left join make m on d.dealer_id = m.dealer_id where d.dealer_id &gt; 6 for (Dealer dealer : dealers) { Set&lt;Make&gt; make = dealer.getDealerMakes() // no SQL query. The makes are already loaded } </code></pre>
 

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