users@jpa-spec.java.net

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

From: Linda DeMichiel <linda.demichiel_at_oracle.com>
Date: Mon, 15 Apr 2013 16:41:57 -0700

On 4/15/2013 3:22 PM, Pinaki Poddar wrote:
> 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?
>

Yes

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