title: How to use PreparedStatement efficiently?
body: <p>I like to use the DAO pattern and have a class which do all my SQL request for a particular table and JPA entity. I have for example something like:</p>
  
  <pre><code>public class MyDao {
  
      @PersistenceContext(name = "mycontext")
      private EntityManager entityManager;
  
      public List&lt;MyEntity&gt; find(String code)  {
  
          return getEntityManager()
              .createQuery("FROM MyEntity e WHERE e.code = :code")
              .setParameter("code", code)
              .getResultList();
  
      }
  
  }
  </code></pre>
  
  <p>But I also know we can use named query directly on the entity class with a static method (I don't like this way):</p>
  
  <pre><code>@Entity
  @Table
  @NamedQueries({
      @NamedQuery(name = "find", query = "FROM MyEntity e WHERE e.code = :code")
  })
  public class MyEntity {
  
      ...
  
      public static List&lt;MyEntity&gt; find(EntityManager entityManager, String code) {
  
          return entityManager.createNamedQuery("find", MyEntity.class)
              .setParameter("code", code)
              .getResultList();
  
      }
  
  }
  </code></pre>
  
  <p>Is one of those method better than the other one ? If I want to execute the same SQL query thousands of times in the same transaction, is both methods keep in JPA memory (or somewhere else) the prepared statement ? Which seems to be a good practise in this case. I would think the second method does it because it's static but not the first one. Am I wrong ? </p>