cl.model.dao.EmpleadoDAO.java Source code

Java tutorial

Introduction

Here is the source code for cl.model.dao.EmpleadoDAO.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 cl.model.dao;

import cl.model.pojos.Employee;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Query;
import java.util.List;

/**
 *
 * @author Erick
 */

public class EmpleadoDAO {

    public void ingresarEmpleado(Employee emp) {
        SessionFactory sf = null;
        Session session = null;
        Transaction txn = null;

        try {
            sf = HibernateUtil.getSessionFactory();
            session = sf.openSession();
            txn = session.beginTransaction();
            session.save(emp);
            txn.commit();
            session.close();
        } catch (Exception e) {
            txn.rollback();
            throw new RuntimeException("No se pudo guardar detalles de empleado");
        }

    }

    public String consultarEmpleado(int codigo) {
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        Employee emp = (Employee) session.get(Employee.class, codigo);
        session.close();
        if (emp != null) {
            return "El empleado con codigo " + emp.getId() + "cuyo nombre es " + emp.getName()
                    + "ocupa la posicion de " + emp.getRole() + " y fue ingresado el sistema la fecha"
                    + emp.getInsertTime();
        } else {
            return "El codigo de empleado " + codigo + "no pudo ser encontrado";
        }
    }

    public List<Employee> verEmpleados() {
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        Query query = session.createQuery("from Employee");
        List<Employee> lista = query.list();
        session.close();
        return lista;
    }
}