persistence@glassfish.java.net

Re: Dynamically creating named queries

From: Markus Fuchs <Markus.Fuchs_at_Sun.COM>
Date: Mon, 18 Jun 2007 09:31:52 -0700

Hi Farrukh,

take a look at the EntityManager's

public Query createQuery(String qlString);

method. Examples for JPA-QL queries can be found in section 4.13 of the
JPA spec. An example for a dynamic query definition and execution is:

public List findWithName(String name) {
   return em.createQuery(
   "SELECT c FROM Customer c WHERE c.name LIKE :custName")
   .setParameter("custName", name)
   .setMaxResults(10)
   .getResultList();
}

As Lance mentioned, please use parameter markers instead of concating
the parameters directly into the qlString query string.

-- markus.

Farrukh S. Najmi wrote:
> Hello,
>
> In my application I need to dynamically create named queries based on
> configuration data for my application.
> I cannot statically define NamedQuery annotation in my code but instead
> need to create a NamedQuery through code.
>
> I assume this is possible? Is so, can someone please suggest how to do
> this. Thanks you for your help.
>
>