title: Can I limit query results of a Spring Data query method that uses a JPQL named query?
body: <p>I have a named JPQL query which I would like to use in a Spring Data repository interface.  Furthermore, I would to have it return just the first result, or null if there are no matching results.</p>
  
  <p>From what I have been able to determine, there is no way to limit the number of results within a JPQL query.  I cannot just declare the return type as the entity class, as a <code>IncorrectResultSizeDataAccessException</code> will be thrown if more than one result is returned by the query.</p>
  
  <p>For regular (non-JPQL) query methods,  using the keywords <code>first</code> or <code>top</code> (as detailed in the <a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result" rel="nofollow">Spring Data JPA docs</a>).  Named queries can be included in a repository interface by specifying a method name matching the name of the named query (again, as detailed in the <a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#_declaring_interfaces" rel="nofollow">Spring Data JPA docs</a>).  However, I do not see any way to combine these two: to return just the first result of a named query in a repository interface.</p>
  
  <p>Here is a concrete example:</p>
  
  <pre><code>public interface ExampleRepository extends JpaRepository&lt;Example, Integer&gt; {
      // Using "first" or "top" can return just the first value
      Example findFirstByValueNotOrderByValueDesc(String value);
  
      // Using the "Example.findMatchingComplicatedCriteria" named query to return all matching values
      List&lt;Example&gt; findMatchingComplicatedCriteria(@Param("value") String value);
  
      // TODO: How do I make something like this work?
      // Example firstFindMatchingComplicatedCriteria(@Param("value") String value);
  }
  
  @Entity
  @NamedQuery(name = "Example.findMatchingComplicatedCriteria",
          query = "SELECT e from Example e WHERE e.value &lt;&gt; :value ORDER BY e.value DESC")
  public class Example {
      @Id public Integer id;
      public String value;
  }
  </code></pre>
  
  <p>I am aware that I could use an EntityManager directly, but I would like to do this all directly from the repository interface, if possible.  The other workaround would be to have the repository return the list, and have my application code pull out the first element; again, something I'm wondering if I can avoid.  I am also aware that I could use a native query to achieve this functionality.</p>
  
  <p>Ultimately, my question is thus: can I have a Spring Data repository interface method use a named query and return a single result?  Barring that, is there an issue open for this?  I didn't find anything in the Spring Data issue tracker, but my search fu might be failing me.</p>