Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria - how to limit join results to a single entity type?

Ok, so the following query:

SELECT O.*, P.* FROM ORDERS O, PRODUCT P WHERE
    O.ORDER_ID=P.ORDER_ID AND P.ID=’1234’;

can be done with Criteria as follows:

List ordersAndProducts = session.createCriteria(Order.class)
    .setFetchMode(“products”,FetchMode.JOIN)
    .add(Restrictions.eq(“id”,”1234”))
    .list();

but here Criteria.list() returns a List<Object[]> where Object[0] is an Order and Object[1] is a Product for each element in the List.

But how can I do the following SQL with Criteria:

SELECT O.* FROM ORDERS O, PRODUCT P WHERE 
    O.ORDER_ID=P.ORDER_ID AND P.ID=’1234’;

In other words, I want Criteria.list() to give me a List<Order>, I don't care about the Products. I've tried using createAlias() instead of setFetchMode() but the results are the same, and Projections don't let you specify an entity, only a property.

like image 873
mluisbrown Avatar asked Oct 15 '25 04:10

mluisbrown


1 Answers

You can use .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) on the criteria.

List ordersAndProducts = session.createCriteria(Order.class)
    .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
    .setFetchMode(“products”,FetchMode.JOIN)
    .add(Restrictions.eq(“id”,”1234”))
    .list();

Now you retrieve all orders with eagerly loaded products.

like image 116
Olivier Heidemann Avatar answered Oct 16 '25 17:10

Olivier Heidemann



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!