Difference between criteria and detached criteria in hibernate?
The detached criteria allows you to create the query without Session
. Then you can execute the search in an arbitrary session.
In fact you should think carefully when using a detached criteria
using another, or a new, session (no cache, and creation of the session).
They are most useful for join conditions, subselects, and to query outside the current session.
Another common use is for code reuse. Many developers declare them as static
queries and execute them using the underlying session from different DAO
.
Using a DetachedCriteria is exactly the same as a Criteria except you can do the initial creation and setup of your query without having access to the session. When it comes time to run your query, you must convert it to an executable query with getExecutableCriteria(session)
.
This is useful if you are building complicated queries, possibly through a multi-step process, because you don't need access to the Session everywhere. You only need the Session at the final step when you run the query.
Under the hood, DetachedCriteria uses a CriteriaImpl which is the same class you get if you call session.createCriteria()
.
-Detached criteria is very good alternate when the hibernate session is not present.
-The criteria are online, which means that it uses Session class object. But the detached criteria is offline because it doesn't need a session.
-Then the detach criteria allow code reusability.
public static void main(String [] args) throws Exception {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
System.out.println("By using criteria");
Criteria cr=session.createCriteria(Student.class);
cr.add(Restrictions.eq("gender", "male"));
cr.addOrder(Order.asc("stud_id"));
List<Student> res=((Criteria) cr).list();
for(int i=0;i<res.size();i++)
{
System.out.print( res.get(i).getStud_id()+"\t");
System.out.println(res.get(i).getName());
}
System.out.println("\n\nBy using Detached criteria");
DetachedCriteria dcr = DetachedCriteria.forClass(Student.class).add(Property.forName("gender").eq("male"));
dcr.addOrder(Order.desc("stud_id"));
List<Student> results = dcr.getExecutableCriteria(session).list();
for(int i=0;i<results.size();i++)
{
System.out.print( results.get(i).getStud_id()+"\t");
System.out.println(results.get(i).getName());
}
Click here for implementation notes.