Reduce the number of queries needed by hibernate
<p>When populating a table from a database using hibernate, one would ideally want to use the least amount of queries so their application is quick. Ideally you would not want to do more queries than there are columns in the table you are constructing, as a group by query would allow you to populate all the rows. So if you had m columns, and n rows, you would only want to perform m queries.</p>

<p>However I find it hard to achieve this within my Daos without writing new methods. Let's say you were dealing with an Entity called Employee, and you wanted to calculate average number of hours worked, you would then need 2 methods:</p>

<pre><code>public interface EmployeesDao
{
    public List&lt;Double&gt; averageOfHoursWorked(List&lt;Integer&gt; ids);
    public double averageOfHoursWorked(Integer id);
}
</code></pre>

<p>So when you want to create a table, you would use the method accepting a list, but when you are just dealing with a single employee you would use the one which takes a single ID.</p>

<p>But I don't want to write 2 methods, I just want to write one ideally. But if I write one method, I end up using a for loop which makes a whole bunch of queries instead of just one:</p>

<pre><code>    // THIS IS BAD, creates many queries
    List&lt;Integer&gt; ids = Arrays.asList(1,3,5,99, 1921);
    for (Integer id : ids) {
        double avg = dao.averageOfHoursWorked(id);
        // .... doing some table stuff with avg...
    }

    // THIS IS GOOD, only 1 query, yet now I must write more code ):
    List&lt;Double&gt; avgs = dao.averageOfHoursWorked(ids);
    for (Double avg : avgs) {
        // .... doing some table stuff with avg...
    }
</code></pre>

<p>So I know the second version is much quicker, but it takes me longer to code then. But as I was writing this I figured I could do something like this:</p>

<pre><code>class EmployeesDaoImp implements EmployeesDao {

    @Override
    public double averageOfHoursWorked(Integer id) {
        return averageOfHoursWorked(Arrays.asList(id)).get(0);
    }
}
</code></pre>

<p>Then I would just have to write <code>List&lt;Double&gt; averageOfHoursWorked(List&lt;Integer&gt; ids)</code>, is this a good idea? Does someone have a more elegant way of making tables in general with hibernate? Maybe a builder pattern or something would be nicer like: </p>

<p><code>Table table = dao.buildTable().withIds(ids).columnId().columnAvgHoursWorked().columnDaysOff()</code></p>

<p>where columnId() would give you a column of ids, columnAvgHoursWorked, would give you another column with the hours worked and so on. What is the most optimal way of making tables with hibernate, requiring the least amount of queries and code.</p>