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.
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"));