1 package com.iqjava.employee; 2 3 import org.hibernate.HibernateException; 4 import org.hibernate.Session; 5 import org.hibernate.Transaction; 6 import java.util.List; 7 import java.util.Iterator; 8 import com.iqjava.util.HibernateUtil; 9 10 public class ExecutionClass { 11 12 public static void main(String[] args) { 13 14 ExecutionClass obj = new ExecutionClass(); 15 Long empId1 = obj.saveEmployee("John"); 16 Long empId2 = obj.saveEmployee("Paul"); 17 Long empId3 = obj.saveEmployee("Bill"); 18 obj.listEmployee(); 19 System.out.println("Updating emp3...."); 20 obj.updateEmployee(empId3, "Michael"); 21 System.out.println("Deleting emp2...."); 22 obj.deleteEmployee(empId2); 23 System.out.println("List employees...."); 24 obj.listEmployee(); 25 } 26 27 public Long saveEmployee(String employeeName) 28 { 29 Session session = HibernateUtil.getSessionFactory().openSession(); 30 Transaction transaction = null; 31 Long empId = null; 32 try { 33 transaction = session.beginTransaction(); 34 Employee emp = new Employee(); 35 emp.setEmployeeName(employeeName); 36 empId = (Long) session.save(emp); 37 transaction.commit(); 38 } catch (HibernateException e) { 39 transaction.rollback(); 40 e.printStackTrace(); 41 } finally { 42 session.close(); 43 } 44 return empId; 45 } 46 47 public void listEmployee() 48 { 49 Session session = HibernateUtil.getSessionFactory().openSession(); 50 Transaction transaction = null; 51 try { 52 transaction = session.beginTransaction(); 53 List emps = session.createQuery("from Employee").list(); 54 for (Iterator iterator = emps.iterator(); iterator.hasNext();) 55 { 56 Employee emp = (Employee) iterator.next(); 57 System.out.println(emp.getEmployeeName()); 58 } 59 transaction.commit(); 60 } catch (HibernateException e) { 61 transaction.rollback(); 62 e.printStackTrace(); 63 } finally { 64 session.close(); 65 } 66 } 67 68 public void updateEmployee(Long empId, String employeeName) 69 { 70 Session session = HibernateUtil.getSessionFactory().openSession(); 71 Transaction transaction = null; 72 try { 73 transaction = session.beginTransaction(); 74 Employee emp = (Employee) session.get(Employee.class, empId); 75 emp.setEmployeeName(employeeName); 76 transaction.commit(); 77 } catch (HibernateException e) { 78 transaction.rollback(); 79 e.printStackTrace(); 80 } finally { 81 session.close(); 82 } 83 } 84 85 public void deleteEmployee(Long empId) 86 { 87 Session session = HibernateUtil.getSessionFactory().openSession(); 88 Transaction transaction = null; 89 try { 90 transaction = session.beginTransaction(); 91 Employee emp = (Employee) session.get(Employee.class, empId); 92 session.delete(emp); 93 transaction.commit(); 94 } catch (HibernateException e) { 95 transaction.rollback(); 96 e.printStackTrace(); 97 } finally { 98 session.close(); 99 } 100 } 101 102 } 103 104