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:
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); cq.select(product); 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:
In the next sections we will see more examples of querying entities.
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial