19

when to use detached criteria? and what is the advantage we get by using detached criterias instead of normal criteria?

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Some.class);


DetachedCriteria criteria = DetachedCriteria.forClass(Some.class);

Thanks!

user1016403
  • 12,151
  • 35
  • 108
  • 137
  • 1
    http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html#querycriteria-detachedqueries – Reddy Jan 19 '12 at 12:24

2 Answers2

17

As per docs

Some applications need to create criteria queries in "detached mode", where the Hibernate session is not available. This class may be instantiated anywhere, and then a Criteria may be obtained by passing a session to getExecutableCriteria(). All methods have the same semantics and behavior as the corresponding methods of the Criteria interface.

Mukul Goel
  • 8,387
  • 6
  • 37
  • 77
user998692
  • 5,172
  • 7
  • 40
  • 63
11

'Detached from session object'

Detached Criteria may be used in two scenarios:

  1. Building criteria query with no session object:
    Session only requires during executing the query/submitting the query to database, not while building the query.

    Ex:

        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Department.class);
        detachedCriteria.add(Restrictions.eq("DEPTID", 1));
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("DEPTID"));
        detachedCriteria.setProjection(projectionList);
    
       //Add more
        .............................
    

    In the above code do you find any necessity of having session object for building such a criteria query? absolutely NO.

  2. Building same criteria query for multiple times:
    Build it once irrespective of the session object, and can be used whenever/wherever you want.

Finally when session object is available, use the above query with session as follows:

detachedCriteria.getExecutableCriteria(session).list();
Jagadeesh
  • 2,730
  • 6
  • 30
  • 45