Thursday, July 30, 2009

Using Named Queries

Named queries make it easy to reuse SQL queries in JPA Entity Beans & Controllers and they are also more readable than inline SQL. I'm not sure, but my guess is they probably run faster too.

There are two steps.

1. Add Named Queries as a comma delimited list before your Entity bean's class definition, like so (Remember that the queries are in QL, not SQL. It's SQL like syntax, but you're manipulating the Java objects, not the underlying SQL, so name your "tables" and "columns" appropriately):
@Entity
@Table(name = "MY_TABLE", catalog = "", schema = "")
@NamedQueries({
@NamedQuery(name = "SchedJob.findAll", query = "SELECT s FROM SchedJob s"),
...
)})
public class MyObject implements Serializable {
...


2. Use the named query in your controller by calling createNamedQuery on your entity manager.
    public List findByText(String text) {
EntityManager em = getEntityManager();
try {
Query q = em.createNamedQuery("MyObject.findByText");
q.setParameter("text", text);
return q.getResultList();
} finally {
em.close();
}
}

You can also return a single result and some other things (Google for the Javadocs).

A more compact format is:
Teachers teacher = (Teachers) 
em.createNamedQuery("Teachers.findByGName").setParameter("gName",
gNameString).getSingleResult();

or
List teachers = (Teachers) 
em.createNamedQuery("Teachers.findByGName").setParameter("gName",
gNameString).getResultList();

No comments:

Labels

Blog Archive

Contributors