title: Is there a way to reduce the amount of boiler-plate code associated with a CriteriaQuery (in JPA 2.0)?
body: <p>I love the type safety <a href="http://java.sun.com/javaee/6/docs/api/javax/persistence/criteria/CriteriaQuery.html" rel="noreferrer">CriteriaQuery</a> brings ing JPA 2.0 but it also brings a bit of boiler-plate code. For example, let say I have an entity called NamedEntity, which simply has an id and a String field called "name" (assume it has the unique constraint set to true). Here's what the NamedEntityManager might look like:</p>
  
  <pre><code>public class NamedEntityManager
  {
      //inject using your framework
      EntityManager entityManager;
  
      //retrieve all existing entities of type NamedEntity from DB
      public Iterable&lt;NamedEntity&gt; queryAll()
      {
          CriteriaBuilder builder = entityManager.getCriteriaBuilder();
          CriteriaQuery&lt;NamedEntity&gt; query = builder.createQuery(NamedEntity.class);
          return entityManager.createQuery(query).getResultList();
      }
  
      //retrieve a single entity of type NamedEntity from DB using specified name
      public NamedEntity queryByName(String name)
      {
          CriteriaBuilder builder = entityManager.getCriteriaBuilder();
          CriteriaQuery&lt;NamedEntity&gt; query = builder.createQuery(NamedEntity.class);
          Root&lt;NamedEntity&gt; root = query.from(NamedEntity.class);
          query = query.where(root.&lt;NamedEntity&gt;get("name").in(name));
  
          //skipped the try/catch block for the sake of brevity
          return entityManager.createQuery(query).getSingleResult();
      }
  }
  </code></pre>
  
  <p>Is there a way to condense the code in order to avoid copying/pasting the same lines of code into each query method? Perhaps somehow reuse the CriteriaQuery object?</p>