30 Aralık 2013 Pazartesi

Hibernate Detached Criteria


Aşağıdaki gibi bir detached criteria sorgusu ile hibernate'de subquery oluşturmak mümkün.


public List<Mother> find(String aProperty){
Session session = getSession(); // Create hibernate session
Criteria motherCrit = s.createCriteria(Mother.class);
// Create sub query
DetachedCriteria childListCrit = DetachedCriteria.forClass(Child.class);
childListCrit.add(Restrictions.eq("aProperty", aProperty));
childListCrit.setProjection(Projections.distinct(Projections.property("mother.id")));
motherCrit.add(Subqueries.propertyIn("id", childListCrit));
return motherCrit.list();
}
Hibernate tarafından aşağıdakine benzer bir SQL oluşturulacaktır:

select
mother_.*
from
Mother mother_
where
and mother_.id in (
select
distinct child_.id as y0_
from
PAYS.CHILD child_
where
child_.A_PROPERTY=?
)
Aşağıdaki bağlantılardan daha ayrıntılı bilgi alınabilir:

http://stackoverflow.com/questions/300491/how-to-get-distinct-results-in-hibernate-with-joins-and-row-based-limiting-pagi http://stackoverflow.com/questions/13075390/hibernate-subquery-detachedcriteria
http://stackoverflow.com/questions/3738555/hibernate-criteria-subquery
http://www.roseindia.net/hibernate/hibernate4/hibernateCriteriaDetachedSubQueries.shtml
http://www.coderanch.com/t/415182/ORM/databases/Write-Query-Hibernate