HibernateGenericDAO.GenericHibernateDAO.java Source code

Java tutorial

Introduction

Here is the source code for HibernateGenericDAO.GenericHibernateDAO.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 HibernateGenericDAO;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.*;

/**
 *
 * @author edwin
 * https://developer.jboss.org/wiki/GenericDataAccessObjects
 * @param <T>
 * @param <ID>
 */
@SuppressWarnings("FieldMayBeFinal")
public abstract class GenericHibernateDAO<T, ID extends Serializable> implements IGenericHibernateDAO<T, ID> {

    private Class<T> persistentClass;
    private Session session;

    protected static SessionFactory fabrica_sesiones;
    static {
        GenericHibernateDAO.fabrica_sesiones = new Configuration().configure().buildSessionFactory();
    }

    public GenericHibernateDAO() {
        /* ATENCION!!!!!!
        ParameterizedType esta en dos librerias: una en java.lang.reflect y otra
        en org.hibernate.usertype
        NOTA: java.lang parece ser la solucion
        */
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }

    //@SuppressWarnings("unchecked")  
    protected void abrirSession() {
        if (session != null && session.isConnected()) {
            throw new IllegalStateException("El objeto Session sigue conectado");
        }
        this.session = GenericHibernateDAO.fabrica_sesiones.openSession();
    }

    protected void cerrarSession() {
        if (!session.isConnected()) {
            throw new IllegalStateException("El objeto Session no se encuentra conectado");
        }
        this.session.close();
    }

    protected Session getSession() {
        if (session == null)
            throw new IllegalStateException("Session has not been set on DAO before usage");
        return session;
    }

    public Class<T> getPersistentClass() {
        return persistentClass;
    }

    /**
     *
     * @param id
     * @param lock
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public T findById(ID id, boolean lock) {
        this.abrirSession();
        T entity;
        if (lock)
            entity = (T) getSession().get(getPersistentClass(), id, LockMode.UPGRADE);
        else
            entity = (T) getSession().get(getPersistentClass(), id);
        this.cerrarSession();
        return entity;
    }

    /**
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<T> findAll() {
        List<T> res = findByCriteria();
        return res;
    }

    /**
     * findByExample recupera objetos en funcin de una instancia ejemplo de la cual
     * se ignoran ciertos campos en la comparacin con otras entidades del mismo tipo.
     * 
     * @param exampleInstance debe ser una instancia con los atributos de inters 
     * previamente seteados
     * @param excludeProperty debe ser un array de strings que indique los CAMPOS
     * que deben ser ignorados
     * @return 
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
        this.abrirSession();
        Criteria crit;
        crit = getSession().createCriteria(getPersistentClass());
        Example example = Example.create(exampleInstance);
        for (String exclude : excludeProperty) {
            example.excludeProperty(exclude);
        }
        crit.add(example);
        List<T> res = crit.list();
        this.cerrarSession();
        return res;
    }

    @Override
    public T findUniqueByExample(T exampleInstance, String[] excludeProperty) throws Exception {
        try {
            List<T> res = this.findByExample(exampleInstance, excludeProperty);
            if (res.size() > 1) {
                throw new Exception("ERROR Mltiples resultados obtenidos");
            } else {
                return res.get(0);
            }
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     *
     * @param entity
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public T makePersistent(T entity) {
        this.abrirSession();
        this.getSession().beginTransaction();
        getSession().saveOrUpdate(entity);
        this.getSession().getTransaction().commit();
        this.cerrarSession();
        return entity;
    }

    /**
     *
     * @param entity
     */
    @Override
    public void makeTransient(T entity) {
        this.abrirSession();
        getSession().beginTransaction();
        try {
            getSession().delete(entity);
            this.getSession().getTransaction().commit();
        } catch (Exception e) {
            this.getSession().getTransaction().rollback();
        }
        this.cerrarSession();
    }

    /*
      public void flush() {
    getSession().flush();
      }
        
      public void clear() {  
    getSession().clear();  
      }  
    */
    /** 
     * Use this inside subclasses as a convenience method. 
     * @param criterion
     * @return 
     */
    @SuppressWarnings("unchecked")
    protected List<T> findByCriteria(Criterion... criterion) {
        this.abrirSession();
        Criteria crit = getSession().createCriteria(getPersistentClass());
        for (Criterion c : criterion) {
            crit.add(c);
        }
        List<T> lista = crit.list();
        this.cerrarSession();
        return lista;
    }

}