title: CriteriaBuilder query with sub-query, single column result, max function and generic types using metamodel
body: <p>My objective is to replace an old JPQL query with a generic type-safe helper method using <code>javax.persistence.metamodel</code> and <code>javax.persitence.criteria</code>.</p>
  
  <p>The query is essentially</p>
  
  <pre><code>select * from table 
      where field1 = arg1 
          and field2 = arg2 
          and field3 = (select max (field3) 
                          from table 
                          where field1 = arg1 
                              and field2 = arg2 
                              and field3 &lt;= arg3
                       )
  </code></pre>
  
  <p>Admittedly this is maybe too specialized a query to generalize but I see the need for 2 or 3 other more generic helpers which I can model on this solution.</p>
  
  <p>I have been googling the Criteria documentation (one problem is it's easy to surf a google search result list and mistakenly move from a <code>javax.persitence</code> page to a <code>JBoss Hibernate</code> page... and they are NOT the same).</p>
  
  <p>I have obviously not found a one-stop shop that tells me all I need to know:</p>
  
  <ul>
  <li>how to select a single field in a <code>CriteriaQuery</code></li>
  <li>how to structure a subquery in a <code>CriteriaQuery</code> <code>Expression</code></li>
  <li>how to write a max aggregate function call using <code>CriteriaBuilder</code></li>
  <li>how to properly use Static Metamodel attributes to specify generic classes in a <code>CriteriaBuilder</code> query, when the table being queried has a composite key which is mapped by composite key class (using <code>@EmbeddedId</code>)</li>
  </ul>