Querying Entities

The EntityManager interface can be used by the application to query for particular entities using JPQL and Criteria API. This article is explaining you about both ways of querying the Entity.

Querying Entities - How to Query entities in JPA 2.1?

In this section you will learn how to query the entities?

In JPA each entity is mapped to a particular table and identify by a primary key. So, if you want to fetch some data from database (in the form of entities) you have to use the EntityManager interface.

The EntityManager interface method provides many methods for interacting with the persistence unit in order to perform CRUD operations. There following two ways in which you can query underlying entities:

  • The Java Persistence Query Language: The Java Persistence query language or JPQL is a simple, string-based query language which is similar to the SQL. But it is used to query the entities and their relationships. The JPA persistence provide will automatically translate this JPQL into SQL and execute against database. The persistence provider will then fetch the data, populate the entities and return it to the calling program.
  • The Criteria API: The Criteria API is very useful and it is used to create typesafe queries using Java programming language APIs. It is used to create queries for entities and their relationships.

Example of JPQL

The JPQL is platform-independent object oriented query language which is used to query the underlying entities. The JPQl is  used to perform SELECT queries, UPDATE and DELETE queries.

Here is an example of select query:

SELECT p FROM Product p ORDER BY p.productName

Example of Criteria API

You can use the Criteria API for querying the underlying data store. The Criteria Query works regardless of the underlying database.

Here is simple example of Criteria Query:

EntityManager em = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> product = cq.from(Product.class);
TypedQuery<Product> q = em.createQuery(cq);
List<Product> allProducts = q.getResultList();

How to create a Criteria Query?

The javax.persistence.criteria.CriteriaBuilder interface can be used to construct the Criteria Query. This interface can be used for:

  • Criteria queries
  •  Selections
  •  Expressions
  •  Predicates
  •  Ordering

In the next sections we will see more examples of querying entities.

Read more JPA 2.1 tutorials.

Share on Google+Share on Google+

Querying Entities

Posted on: November 28, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Querying Entities  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image