Detached queries and subqueries by R4R Team

The DetachedCriteria class allows to create a query outside the scope of a session and then execute it using an arbitrary Session.

DetachedCriteria query = DetachedCriteria.forClass(Student.class)

    .add( Property.forName("sex").eq('M') );


Session session = new Configuration().configure().buildSessionFactory();

Transaction txn = session.beginTransaction();

List results = query.getExecutableCriteria(session).setMaxResults(100).list();



A DetachedCriteria can also be used to express a subquery. Criterion instances involving subqueries can be obtained via Subqueries or Property.

DetachedCriteria avgWeight = DetachedCriteria.forClass(Student.class)

    .setProjection( Property.forName("weight").avg() );


    .add( Property.forName("weight").gt(avgWeight) )


DetachedCriteria weights = DetachedCriteria.forClass(Student.class)

    .setProjection( Property.forName("weight") );


    .add( Subqueries.geAll("weight", weights) )


Correlated subqueries are also possible:

DetachedCriteria avgWeightForSex = DetachedCriteria.forClass(Student.class, "student2")

    .setProjection( Property.forName("weight").avg() )

    .add( Property.forName("").eqProperty("") );

     session.createCriteria(Student.class, "student")

    .add( Property.forName("weight").gt(avgWeightForSex) )


Leave a Comment:
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!