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

criteria, hibernate, java, sql

Solution

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.

Problem

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.

Original source