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 br.edu.ifrs.restinga.modulorh.dao; import br.edu.ifrs.restinga.modulorh.modelo.Setor; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; /** * * @author denilson */ public class SetorDAO { private Session sessao; public SetorDAO() { /*Abre uma sessao com o banco */ sessao = HibernateUtil.getSessionFactory().openSession(); } public void cadastrar(Setor setor) { try { if (setor.getSetor().getId() == null) { setor.setSetor(null); } sessao.clear(); Transaction t; t = sessao.beginTransaction(); sessao.save(setor); // Hibernate realizar a operano de insert no banco t.commit(); //gera comit no banco confirmando transao } catch (Exception e) { System.out.println("Erro no SetorDAO - SalvarSetor: " + e.getMessage()); } } public void alterar(Setor setor) { try { if (setor.getSetor().getId() == null) { setor.setSetor(null); } sessao.clear(); Transaction t; t = sessao.beginTransaction(); sessao.saveOrUpdate(setor); t.commit(); } catch (Exception e) { System.out.println("Erro no SetorDAO - alterarSetor: " + e.getMessage()); } } public void excluir(Setor setor) { try { //sessao.clear(); sessao.close(); sessao = HibernateUtil.getSessionFactory().openSession(); Transaction t; t = sessao.beginTransaction(); sessao.createSQLQuery("update setor SET IdSetor = null where IdSetor =" + setor.getId()) .executeUpdate(); sessao.delete(setor); t.commit(); } catch (Exception e) { } } public List<Setor> listarNome(String nome) { sessao.clear(); return sessao.createCriteria(Setor.class).add(Restrictions.like("nome", "%" + nome + "%")) .addOrder(Order.asc("nome")).list(); } public List<Setor> listarSetor() { try { sessao.close(); sessao = HibernateUtil.getSessionFactory().openSession(); return sessao.createCriteria(Setor.class).list(); } catch (Exception e) { return null; } } public Setor carregar(Integer id) { try { sessao.clear(); return (Setor) sessao.get(Setor.class, id); } catch (Exception e) { return null; } } }