Share on Google+Share on Google+

Hibernate Detached Criteria

Advertisement
This section is good discussion about hibernate detached criteria.

Hibernate Detached Criteria

This section is good discussion about hibernate detached criteria.

Detached Criteria in Hibernate :

Detached criteria is very good alternate when the hibernate session is not present. You can say detached criteria is a concept of writing query in detached mode.

You can instantiate this class anywhere. For this you have to import -

org.hibernate.criterion.DetachedCriteria;

Way to write DetchedCriteria -


DetachedCriteria query = DetachedCriteria.forClass(Employee.class);
query.add(Property.forName("name").eq("Som"));

Next you can obtain criteria by passing any arbitrary session to getExecutableCriteria() as -

employeeList = query.getExecutableCriteria(session).list();

Here is an example of detached criteria. Employee is our table. This example show the record of employee named "Som".

package net.roseindia.main;

import java.util.*;
import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;

public class DetachedCriteriaQuery {
public static void main(String[] args) {
DetachedCriteria query = DetachedCriteria.forClass(Employee.class);
query.add(Property.forName("name").eq("Som"));
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
List<Employee> employeeList = new ArrayList<Employee>();
employeeList = query.getExecutableCriteria(session).list();
Iterator it = employeeList.iterator();
while (it.hasNext()) {
Employee employee = (Employee) it.next();
System.out.println("Name : " + employee.getName());
System.out.println("Salary : " + employee.getSalary());
System.out.println("Date of Join : " + employee.getDateOfJoin());
}
session.close();

}
}

Output :

Hibernate: select this_.emp_id as emp1_0_0_, this_.date_of_join as date2_0_0_, this_.name as name0_0_, this_.salary as salary0_0_ from employee this_ where this_.name=?
Name : Som
Salary : 20000
Date of Join : 1999-06-22 00:00:00.0

Download complete source code

Advertisements

Advertisement

Posted on: July 3, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Comments:0