Hibernate and JPA named query example

Hibernate and JPA specification lets you externalize query strings to the mapping metadata, a technique that is called named queries. This allows you to store all queries related to a particular persistent class (or a set of classes) in an XML mapping file or using some simple annotations. 


In any case, The name of the query is used to call it from the application.

Hibernate example:

Supposing that you have the following query in HQL language:
“from Customer c where c.name like :cname”

We can introduce this query in the file Customer.hbm.xml, using the <query> element:

<query name="findCustomerByName"><![CDATA[from Customer c where c.name like :cname]] />

Notice: Named queries don€™t have to be HQL strings; they might even be native SQL que-ries

And here’s how to use your named query:

.setString("cname", name)

JPA Example:

Named queries are typically placed on the entity class that most directly corresponds to the query result, so the Customer entity would be a good location for this named query

query="from Customer c where c.name like :cname")

Then in your EJB, you can use:

public class CustomerServiceBean  {

EntityManager em;

   public Customer findCustomerByName(String name) {
     return em.createNamedQuery("findCustomerByName",Customer.class)
       .setParameter("name", name)
// ...