when to use detached criteria in hibernate?

前端 未结 2 1512
甜味超标
甜味超标 2020-12-28 16:51

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

Criteria criteria = sessionFactory.ge         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 17:20

    '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();
    

提交回复
热议问题