users@jpa-spec.java.net

[jpa-spec users] [jsr338-experts] EntityManagerFactory.addNamedQuery() stores a template?

From: Pinaki Poddar <ppoddar_at_us.ibm.com>
Date: Mon, 15 Apr 2013 15:22:15 -0700

Hello Linda,
    From the JavaDoc of the newly introduced
EntityManagerFactory.addNamedQuery(String name, Query q), I am assuming
that the supplied query q is treated as a template as opposed to an
instance as far as binding parameters are concerned.
Let us consider a simple case

 // we create a query
     EntityManager em = ...;
     Query query = em.createQuery("select p from PObject p where p.name
= :name");
     // and configure it
     query.setFirstResult(51);
    // and bind its parameter to a specific value
     query.setParameter("name", "XYZ");

     // let us declare this query to the persistence unit
     emf.addNamedQuery("x", query);

    // after a while we recall it
        EntityManager em2 = ...;
        Query query2 = em2.cretaeNamedQuery("x");

   // Then according to the JavaDoc the following assertions should succeed
       assertTrue(query != query2); // the query we declared is a template
and hence what is recalled is essentially a new one
       assertEquals(51, query2.getFirstResult()); // but the new one
retains the first result position and other configuration of the template

  // but the binding parameters are not memorized i.e

      try {
           query2.getResultList();
           fail("Expected the query execution to fail because the declared
parameter [name] is not bound");
      } catch (Exception ex) {
          ex.printStackTrace();
      }

  Will you please confirm if my reading of the spec in this regard is
correct or not?


Regards --

Pinaki Poddar
Chair, Apache OpenJPA Project http://openjpa.apache.org/
JPA Expert Group Member
Application & Integration Middleware