Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JPA2 criteria API without Metamodel on a List property

How can I formulate the following JPA2 criteria query without using the metamodel classes:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
cq.where(cb.isEmpty(emp.get(Employee_.projects)));
cq.select(emp);

I would like to use:

cq.where(cb.isEmpty(emp.get("projects")));

But I cant figure out how to convert the Path to an Expression, which is needed by cb.isEmpty...

Thanks.

like image 783
jbandi Avatar asked Aug 30 '10 22:08

jbandi


People also ask

How use JPA Criteria API?

Let's see it step by step: Create an instance of Session from the SessionFactory object. Create an instance of CriteriaBuilder by calling the getCriteriaBuilder() method. Create an instance of CriteriaQuery by calling the CriteriaBuilder createQuery() method.

Which method can be used to sort the extracted results using criteria queries?

The ORDER BY clause is used to sort the data and arrange them either in ascending or descending order. The CriteriaQuery interface provides orderBy() method to define the type of ordering.

What is metamodel in JPA?

JPA (Java persistence API) metamodel classes are classes that describe the structure of JPA entity classes (classes used to store database state as Java objects). They enable you to write Java code for creating database queries in a typesafe way.

Why do we need API criteria?

The Criteria API is used to define queries for entities and their persistent state by creating query-defining objects. Criteria queries are written using Java programming language APIs, are typesafe, and are portable. Such queries work regardless of the underlying data store.


1 Answers

Try this:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Employee.class);
Root emp = cq.from(Employee.class);
cq.where(cb.isEmpty(emp.<List<Project>>get("projects")));
cq.select(emp);

Or, using a Path variable:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Employee.class);
Root emp = cq.from(Employee.class);
Path<List<Project>> projects = emp.get("projects"));
cq.where(cb.isEmpty(projects);
cq.select(emp);

Reference

  • javax.persistence.criteria API
    • <Y> Path<Y> Path.get(String):
like image 78
Pascal Thivent Avatar answered Sep 28 '22 00:09

Pascal Thivent