br.edu.ifrs.restinga.modulorh.dao.ServidorDAO.java Source code

Java tutorial

Introduction

Here is the source code for br.edu.ifrs.restinga.modulorh.dao.ServidorDAO.java

Source

/*
 * 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.Servidor;
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 ServidorDAO {
    private Session sessao;

    public ServidorDAO() {

        /*Abre uma sessao com o banco */
        sessao = HibernateUtil.getSessionFactory().openSession();

    }

    public void cadastrar(Servidor servidor) {

        try {
            Transaction t;
            t = sessao.beginTransaction();
            sessao.save(servidor); // Hibernate realizar a operano de insert no banco 
            t.commit(); //gera comit no banco confirmando transao

        } catch (Exception e) {
            System.out.println("Erro no ServidorDAO - SalvarServidor: " + e.getMessage());
        }
    }

    public void alterar(Servidor servidor) {

        try {
            sessao.clear();
            Transaction t;
            t = sessao.beginTransaction();
            sessao.saveOrUpdate(servidor);
            t.commit();
        } catch (Exception e) {
            System.out.println("Erro no ServidorDAO - alterarServidor: " + e.getMessage());

        }

    }

    public void excluir(Servidor servidor) {

        try {
            sessao.clear();
            Transaction t;
            t = sessao.beginTransaction();
            sessao.delete(servidor);
            t.commit();

        } catch (Exception e) {

        }
    }

    public List<Servidor> listarNome(String nome) {
        sessao.clear();
        return sessao.createCriteria(Servidor.class).add(Restrictions.like("nome", "%" + nome + "%"))
                .addOrder(Order.asc("nome")).list();

    }

    public List<Servidor> listarServidor() {
        try {
            sessao.clear();
            return sessao.createCriteria(Servidor.class).list();
        } catch (Exception e) {
            return null;
        }

    }

    public Servidor carregar(Integer id) {
        try {
            sessao.clear();
            return (Servidor) sessao.get(Servidor.class, id);
        } catch (Exception e) {
            return null;
        }
    }
}