Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can create any object in your QL using the "new" syntax - your class just needs a constructor that takes the values returned by your query.</p> <p>For example, with a class like DepartmentEmployeeCount, with a constructor:</p> <pre><code>public DepartmentEmployeeCount(String departmentName, Integer employeeCount) </code></pre> <p>you could use QL something like:</p> <pre><code>SELECT NEW DepartmentEmployeeCount(D.DEPARTMENT_NAME, count(E.id)) from Department D left join D.employees E GROUP BY D.DEPARTMENT_NAME </code></pre> <p>Or if you were just selecting the count(*) you could simply cast the query result to a Number.</p> <p>Alternatively, to do the same without the DepartmentEmployeeCount class, you could leave out the NEW, so:</p> <pre><code>SELECT D.DEPARTMENT_NAME, count(E.id) </code></pre> <p>This would return a <code>List&lt;Object[]&gt;</code> where each list item was an array of 2 elements, departmentName and count.</p> <p>To answer your later question in the comments, to populate all fields of a Department plus a transient employeeCount field, one suggestion would be to do 2 queries. This would still be more efficient than your original query (a subselect for each employee count).</p> <p>So one query to read the departments</p> <pre><code>SELECT D from Department D </code></pre> <p>giving you a <code>List&lt;Department&gt;</code></p> <p>Then a 2nd query returning a temporary array:</p> <pre><code>SELECT D.DEPARTMENT_ID, count(E.id) from Department D left join D.employees E GROUP BY D.DEPARTMENT_ID </code></pre> <p>giving you a <code>List&lt;Object[]&gt;</code> with DEPARTMENT_ID and count in it.</p> <p>Then you use the 2nd list to update the transient count property on your first list. (You could try selecting into a Map to make this lookup easier, but I think that's a Hibernate feature).</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