title: Setting ORDER BY and LIMIT clause on JPA Query
body: <p>I'm very, very new to Hibernate and JPA. I want to be able to apply ORDER BY and LIMIT clauses to a Hibernate(?) query, but am coming up empty. <strong>NOTE: I inherited this code.</strong></p>
  
  <p>Here is the current code:</p>
  
  <pre><code>public SomeCoolResponse getSomeCoolResponse(String myId) {
      String queryString = "select aThing from AWholeBunchOfThings aThing " +
      "join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " + 
      "where saThing.subthing.id = :id";
  
      Query q = getEntityManager().createQuery(queryString);
      q.setParameter("id", myId);
  
      List&lt;MyThings&gt; list = q.getResultList();
  
      if(list.size() &gt; 0) {
          return list.get(0);
      }
      return null;
  }
  </code></pre>
  
  <p>Instead of getting an entire list and then just returning the first result (which is the only one we need), I'd like to be able to apply a <code>LIMIT 0,1</code> clause so that the query will be faster. Also, the query needs to be sorted descending on <code>aThing.created</code> which is a UNIX timestamp integer.</p>
  
  <p>I've tried altering <code>queryString</code> like this:</p>
  
  <pre><code>String queryString = "select aThing from AWholeBunchOfThings aThing " +
      "join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " + 
      "where saThing.subthing.id = :id ORDER BY aThing.created LIMIT 0,1";
  </code></pre>
  
  <p>But Hibernate still returns the entire set.</p>
  
  <p>I've looked at using the JPA CriteriaBuilder API, but it hurt my brain.</p>
  
  <p>I'm a total n00b when it comes to this, and any help is greatly appreciated!</p>