title: Abstracting named queries in an abstract JPA DAO
body: <p>I have an abstract DAO class which uses parameterized types <code>E</code> (Entity) and <code>K</code> (Primary Key). In every entity I have a <code>@NamedQuery</code>. I want to dynamically invoke this named query without knowing its exact name and parameter name.</p>
  
  <p>As an example, imagine the following entity <code>City</code></p>
  
  <pre><code>@Entity(name="CITY")
  @NamedQuery(
      name="findCityByname",
      query="FROM CITY c WHERE name = :CityName"
  )
  public class City { 
      // ...
  }
  </code></pre>
  
  <p>and this <code>CityDao</code></p>
  
  <pre><code>public class CityDao extends AbstractDao&lt;City, Long&gt; {
      public CityDao() {
          super(City.class);
      }   
  }
  </code></pre>
  
  <p>How should I implement the <code>findByName()</code> method in <code>AbstractDao</code> so that I don't need to know the exact name and parameter name?</p>
  
  <pre><code>public abstract class AbstractDao&lt;E, K&gt; implements Dao&lt;E, K&gt; {
  
      @PersistenceContext
      protected EntityManager entityManager;
      protected Class&lt;E&gt; entityClass;
  
      protected AbstractDao(Class&lt;E&gt; entityClass) {
          this.entityClass = entityClass; 
      }
  
      @Override
      public E findByName(String name) {
          try {
              return (E) entityManager
                  .createNamedQuery("findCityByName")
                  .setParameter("CityName", name)
                  .getSingleResult();
          } catch(Exception e) {
              return null;
          }
      }
  
      // ...
  }
  </code></pre>