问题
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.
回答1:
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.
回答2:
Use the createCriteria
method on the Criteria
class for the relationship.
List ordersAndProducts = session.createCriteria(Order.class)
.createCriteria(“products”)
.add(Restrictions.eq(“id”,”1234”))
.list();
You can read the (slightly confusing) documentation about it here.
来源:https://stackoverflow.com/questions/4377249/hibernate-criteria-how-to-limit-join-results-to-a-single-entity-type