Sunday, October 14, 2012

What is Java Persistence Query Language (JPQL) and how to create queries using JPQL

 Java Persistence query language (JPQL):

Java Persistence Query Language (JPQL) is a platform independent object oriented query language defined in Java Persistence API (JPA). JPQL is an one method of querying entities from data store in JPA. JPQL defines queries for entities and their persistent state. JPQL allows to write portable queries that work regardless of the underlying database system.

JPQL is used to make queries against entities stored in a relational database. The query language uses the abstract persistence schemas of entities, including their relationships, for its data model and defines operators and expressions based on this data model. The scope of a query spans the abstract schemas of related entities that are packaged in the same persistence unit. The query language uses an SQL-like syntax to select objects or values based on entity abstract schema types and relationships among them.

Creating Queries Using the Java Persistence Query Language


There are two JPQL methods which are EntityManager.createQuery and EntityManager.createNamedQuery use to query the data stored in database system.

1- JPQL createQuery:

The purpose of createQuery method is to create dynamic queries directly within an Java application business logic. Below is the example of creatQuery method:

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

2- JPQL createNamedQuery:

The purpose of createNamedQuery method is to create static queries which are defined in metadata by using the javax.persistence.NamedQuery annotation.
The @NamedQuery descripe the name of the query which will be used with the createNamedQuery method.

The code pattern of @NamedQuery query is mentioned below:
  
@NamedQuery(
    name="findAllCustomersWithName",
    query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)

Find below createNamedQuery example where @NamedQuery is being used
 
@PersistenceContext
public EntityManager em;
...
customers = em.createNamedQuery("findAllCustomersWithName")
    .setParameter("custName", "Smith")
    .getResultList();

For more information click here

1 comment:

Please enter relevant question and information.