Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package staff.dao.impl; import java.sql.SQLException; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import staff.dao.DeptDao; import staff.table.Dept; import staff.util.HibernateUtil; /** * * @author Chernyshov */ public class DeptDaoImpl implements DeptDao { @Override public void addDept(Dept dept) throws SQLException { Session session = null; try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); session.beginTransaction(); session.save(dept); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (session.isOpen() && session != null) { session.close(); } } } @Override public void delDept(Dept dept) throws SQLException { Session session = null; try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); session.beginTransaction(); session.delete(dept); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (session.isOpen() && session != null) session.close(); } } @Override public Dept getDept(int id) throws SQLException { Dept result = null; Session session = null; try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); result = (Dept) session.get(Dept.class, id); } catch (Exception e) { e.printStackTrace(); } finally { if (session.isOpen() && session != null) session.close(); } return result; } @Override public List<Dept> getDepts() throws SQLException { List<Dept> depts = null; Session session = null; SessionFactory sessionFactory = null; try { sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); depts = session.createCriteria(Dept.class).list(); } catch (Exception e) { e.printStackTrace(); } finally { if (session.isOpen()) { session.close(); sessionFactory.close(); System.out.println("close getDeps"); } } return depts; } @Override public void editDept(Dept dept) throws SQLException { Session session = null; try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); session.beginTransaction(); session.saveOrUpdate(dept); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (session.isOpen() && session != null) session.close(); } } }