public class GeekEmployeeCriteriaExample {
private static SessionFactory sessionFactory;
public static void main(String[] args)
{
//
try {
sessionFactory = new Configuration()
.configure()
.buildSessionFactory();
}
catch (Throwable ex) {
System.err.println(
"Failed to create sessionFactory object."
+ ex);
throw new ExceptionInInitializerError(ex);
}
GeekEmployeeCriteriaExample
geekEmployeeCriteriaObject
= new GeekEmployeeCriteriaExample();
/* As a sample let us add some 10 records so that we
* can see criteria example */
Integer empID1
= geekEmployeeCriteriaObject.addEmployee(
"GeekA", "GeekA", 1000);
Integer empID2
= geekEmployeeCriteriaObject.addEmployee(
"GeekB", "GeekB", 5000);
Integer empID3
= geekEmployeeCriteriaObject.addEmployee(
"GeekC", "GeekC", 10000);
Integer empID4
= geekEmployeeCriteriaObject.addEmployee(
"GeekD", "GeekD", 20000);
Integer empID5
= geekEmployeeCriteriaObject.addEmployee(
"GeekE", "GeekE", 25000);
Integer empID6
= geekEmployeeCriteriaObject.addEmployee(
"GeekF", "GeekF", 30000);
Integer empID7
= geekEmployeeCriteriaObject.addEmployee(
"GeekG", "GeekG", 40000);
Integer empID8
= geekEmployeeCriteriaObject.addEmployee(
"GeekH", "GeekH", 50000);
Integer empID9
= geekEmployeeCriteriaObject.addEmployee(
"GeekI", "GeekI", 35000);
Integer empID10
= geekEmployeeCriteriaObject.addEmployee(
"GeekJ", "GeekJ", 85000);
* /
System.out.println(
"Listing the data via criteria");
System.out.println("-----------------------------");
geekEmployeeCriteriaObject
.listGeekEmployeesByCriteria();
}
// This method List the geekEmployee data whose salary
// greater than 50000
public void listGeekEmployeesByCriteria()
{
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// This will simply return every object that
// corresponds to the GeekEmployee class.
Criteria geekEmployeeCriteria
= session.createCriteria(
GeekEmployee.class);
// As a list we can collect them and can iterate
List geekEmployeeList
= geekEmployeeCriteria.list();
for (Iterator iterator
= geekEmployeeList.iterator();
iterator.hasNext();) {
GeekEmployee employee
= (GeekEmployee)iterator.next();
System.out.print("First Name: "
+ employee.getFirstName());
System.out.print(" Last Name: "
+ employee.getLastName());
System.out.println(" Salary: "
+ employee.getSalary());
}
tx.commit();
}
catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally {
session.close();
}
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname,
int salary)
{
Session session = sessionFactory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
GeekEmployee employee
= new GeekEmployee(fname, lname, salary);
employeeID = (Integer)session.save(employee);
tx.commit();
}
catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally {
session.close();
}
return employeeID;
}
}