Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to just select entity's id using criteria query?

JPQL makes this kind of change very easy:

Select o from Orders as o where....

Select o.id from Orders as o where....

But in Criteria Query:

CriteriaBuilder builder = kem.getCriteriaBuilder();
CriteriaQuery<Orders> query = builder.createQuery(Orders.class);
Root<Order> orders= query.from(Orders.class);
query.select(orders);
....

It looks that the select item is defined by builder.createQuery(Order.class) already without any flexibility.

I know we can use Tuple.class, but other than like is there any better way to just extra id(just one field) from a complicated query? Without such feature criteria query becomase very lack of flexibility.

like image 217
Dreamer Avatar asked Oct 17 '25 18:10

Dreamer


2 Answers

The JPA Metamodel API can be used for this.

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> query = builder.createQuery(String.class);
Root<Order> root = query.from(Orders.class);
query.select(root.get(Orders_.id));

Here, Orders_ is the metamodel class for the Orders entity.

like image 94
manish Avatar answered Oct 21 '25 09:10

manish


Although it can be done with the optional JPA Metamodel API, it can even be done using the plain Criteria API itself.

It looks that the select item is defined by builder.createQuery(Order.class) already without any flexibility.

If you want to select the id of an order, then you shouldn't use createQuery(Order.class), because that could cause the result to be an order instead of an id of an order. You should use the format createQuery(ResultType.class). So if the id is for example a Java Long, then you should use createQuery(Long.class).

So instead of this:

CriteriaBuilder builder = kem.getCriteriaBuilder();
CriteriaQuery<Orders> query = builder.createQuery(Orders.class);
Root<Order> orders = query.from(Orders.class);
query.select(orders);
....

It should be:

CriteriaBuilder builder = kem.getCriteriaBuilder();
CriteriaQuery<Long> query = builder.createQuery(Long.class);
Root<Order> orders = query.from(Orders.class);
query.select("id"); // or query.select(orders.get("id"))
....

You can even navigate using path navigation:

query.select(orders.get("customer").get("address").get("streetNumber"));
like image 22
Devabc Avatar answered Oct 21 '25 10:10

Devabc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!