Hibernate : Finding Object
In this section we will discuss about session.find() method.
Hibernate session.find():
find() method is used for finding the object into the database. This method
is deprecated.
The signatures for the various find() methods are -
public List find(String query);
public List find(String query,Object value, Type type);
public List find(String query,Object[] values, Type[] types);
The basic find() method accepts a string .
you pass query string to the method based on some criteria that need to be
satisfied in order to return a particular object from the database.
find() method returns List because there might be more than one object.
Example :In this example we are using find() method to list such employee whose empId is greater than 4 .
package net.roseindia.main; import java.util.*; import net.roseindia.table.Employee; import net.roseindia.util.HibernateUtil; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.classic.Session; public class MainClass { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); // session is opened Transaction transaction = session.beginTransaction(); List emp = session.find("FROM Employee WHERE id > 4"); Iterator iterator = emp.iterator(); System.out.println("Employee Name\tSalary\tDate of Join"); while (iterator.hasNext()) { Employee employee = (Employee) iterator.next(); System.out.print(employee.getName()); System.out.print("\t\t" + employee.getSalary()); System.out.print("\t" + employee.getDateOfJoin()); System.out.println(); } session.close(); // session is closed } }
Output :
Hibernate: select employee0_.emp_id as emp1_0_, employee0_.date_of_join as date2_0_, employee0_.name as name0_, employee0_.salary as salary0_ from employee employee0_ where employee0_.emp_id>4 Employee Name Salary Date of Join Rowdy 20000 2012-06-27 00:00:00.0 Linda 20000 2010-06-12 00:00:00.0