Joining with Criteria when no hibernate relationship is available:
This seems to be impossible. But there is a solution that could be applied for some situations:
Having two entities Company and Employee, where Employee.company is mapped to Company.id, we have to obtain the companies with respect to one or more employees' attributes.
DetachedCriteria employeeCriteria = DetachedCriteria.forClass(Employee.class);
employeeCriteria.setProjection(Property.forName("company"));
employeeCriteria.add(Restrictions.lt("createdOn", date));
Criteria criteria = session.createCriteria(Company.class);
criteria.add(Property.forName("id").in(employeeCriteria));
List<Company> companies = criteria.list();
The DetachedCriteria is not related to the session so it enables us to create a query outside the scope of the session, and it will be execued at some point using an arbitrary session (in this case it will get executed using the criteria, which is attached to a session).
In this case the DetachedCriteria instance is used as a subquery; the criterion instance is obtained by using the org.hibernate.criterion.Property class.
Here is the query that hibernate built:
Hibernate: select this_.id as id1_0_, this_.created as created1_0_, this_.name as name1_0_ from companies this_ where this_.id in (select this_.company_id as y0_ from employees this_ where this_.createdOn<?)
One can see that the subquery retrieves the employee's company id as specified by the projection that was set on the employeeCriteria.
Having no hibernate mapping from Company to Entity, using this solution resulted in performing one call to DB.
Niciun comentariu:
Trimiteți un comentariu