DEV Community

Cover image for Overview of Queries type in Spring Data JPA
Adya Shukla
Adya Shukla

Posted on

Overview of Queries type in Spring Data JPA

This post deals with types of JPA query available. JPA queries are of 3 types mainly :

  1. Query
  2. NativeQuery
  3. CriteriaQuery

1 Query: It is written in Java Persistence Query Language (JPQL) syntax and used to perform Crud operations.
Query query = getEntityManager().createQuery("SELECT m FROM MenuEntity m WHERE m.id=:id");

There are two subtypes of query as well :
TypedQuery
NamedQuery

a . TypedQuery : JPA can't infer what query result type will be and thus we have to cast the type. JPA provides a special Query sub-type known as a TypedQuery. This is always preferred to use if we know our Query result type beforehand.

TypedQuery<Menu> query
= getEntityManager().createQuery("SELECT m FROM Menu m WHERE m.id=:id", Menu.class); **
In above query we can see Menu type assigned to TypedQuery.

b. NamedQuery : We provide NamedQuery to entity class, which gives a quick way to read Entity related queries. All NamedQueries must have a unique name. If there is a single NamedQuery then we can use @NamedQuery on the entity class, but if there are multiple then we use @NamedQueries and add comma separated @NamedQuery in it.

For example :
@Entity
@NamedQuery(name="Menu.findAll", query="SELECT m FROM Menu m")
public class Menu {
...
}

2 .NativeQuery : NativeQuery is very simple to use as it provide provides flexibility to write queries that are not provided by JPQL syntax.

Select m from Menu m

3 .CriteriaQuery : Criteria queries are mainly useful to build dynamic queries whose exact structure is only known at runtime.

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery q = cb.createQuery(Menu.class);
Root c = q.from(Menu.class);
q.select(c);

What is the difference between using JPQL and Criteria Queries?
JPQL queries are defined as simple strings similar to SQL queries, but criteria queries are defined by creating Java objects that represents query elements.
Whenever we have to build dynamic queries then criteria queries are preferred else its good to use JPQL for simple queries.
Also when we use criteria queries then we can detect errors at compile time itself.

Top comments (0)