br.com.easypoint.dao.EstadoDAO.java Source code

Java tutorial

Introduction

Here is the source code for br.com.easypoint.dao.EstadoDAO.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.com.easypoint.dao;

import br.com.easypoint.model.Administrador;
import br.com.easypoint.model.Estado;
import br.com.easypoint.util.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

/**
 *
 * @author Matheus Souza
 */
public class EstadoDAO {

    Session session;

    public EstadoDAO() {
        this.session = HibernateUtil.getSessionFactory().openSession();
    }

    public void salvar(Estado estado) {
        session.beginTransaction();
        session.saveOrUpdate(estado);
        session.getTransaction().commit();
        session.close();

    }

    public List<Estado> listar() {
        List<Estado> client = session.createCriteria(Estado.class).list();
        session.close();
        return client;
    }

    public void remover(Estado estado) {
        session.beginTransaction();
        session.delete(estado);
        session.getTransaction().commit();
        session.close();
    }

    public Estado buscarPorId(Long id) {
        session.beginTransaction();
        Estado est = (Estado) session.get(Estado.class, id);
        session.close();
        return est;
    }

    public List<Estado> preencheEstado(Long idPais) throws Exception {

        try {
            session = HibernateUtil.getSessionFactory().openSession();
            String jpql = "FROM br.com.easypoint.model.Estado WHERE pais_id = :idPais order by nome";
            Query query = session.createQuery(jpql);
            query.setParameter("idPais", idPais);

            if (!query.list().isEmpty()) {
                return (List<Estado>) query.list();
            }

        } catch (Exception e) {
            throw e;
        }

        return null;
    }

}