title: setMaxResults in JPA combined with fetch join
body: <p>In our application we have a search screen with a couple of filter fields. When you click the search button a query is executed that fetches a couple of results and lists them in a grid.</p>
  
  <p>There can be however a lot of data so we want to limit the amount of returned results to a maximum of 1000. We are using OpenJPA to map the return records back to our model classes and SQL server as the database engine. For a while I have limited the amount of returned results using this code:</p>
  
  <pre><code>return entityManager.createQuery(query).setMaxResults(1000).getResultList();
  </code></pre>
  
  <p>This worked great until I recently added a couple of joins to the original query.</p>
  
  <p>Let's say for example that you would like to get 10 "Contacts". Each contact has 5 addresses. When I perform the following query:</p>
  
  <pre><code>select c from Contact c left join fetch c.address
  </code></pre>
  
  <p>The actual query that is executed selects 50 records (5 rows per contact, 1 for each address). And this for the 10 contacts.</p>
  
  <p>and limit it to <em>10</em> results and check the query that is executed against the database it is translated to "SELECT TOP 10 FROM ...".</p>
  
  <p>This translates to 10 <strong>records</strong>, not 10 entities. So in my example the returned list of contacts would contain 2 contacts with their 5 addresses.</p>
  
  <p>So that brings me to my question: What can I do to ensure the complete data of 10 <strong>entities</strong> is returned instead of the first 10 records?</p>