Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TASK] - Crear clase BaseDao #47

Open
jselvamadrigal opened this issue Jun 20, 2020 · 4 comments
Open

[TASK] - Crear clase BaseDao #47

jselvamadrigal opened this issue Jun 20, 2020 · 4 comments
Labels
task Indica la necesidad de mejoras específicas que son más pequeñas

Comments

@jselvamadrigal
Copy link
Collaborator

La clase BaseDao centralizara las funciones DML como SELECT, UPDATE, INSERT, DELETE, facilitando la creación de clases dao para cada entidad del modelo actual.

@jselvamadrigal jselvamadrigal added the task Indica la necesidad de mejoras específicas que son más pequeñas label Jun 20, 2020
@berroteran berroteran changed the title [TASK] - Crear clase BaseDao 47 [TASK] - Crear clase BaseDao Jun 30, 2020
@berroteran
Copy link
Member

no entiendo el propósito de este issue, favor explicar.
Les recuerdo que se usará el patron DAO, con Hibernate...

@jselvamadrigal
Copy link
Collaborator Author

@berroteran El objetivo de la clase no rompe el patron DAO mas bien facilita su implementación, el objetivo es correctamente plasmado en la descripción, lo que realiza es la centralización de las funciones DML comunes como son SELECT, UPDATE, INSERT, DELETE,


public class BaseDao<T, ID extends Object> implements Closeable {
private final Session SESSION;
  private final String TABLE_NAME;
  private final String HQL_TABLE_NAME;

  /**
   * Constructor por defecto
   * 
   * @param factory el session factory utilizado para la obtención de Session
   * @param entityClass Class del type generico, utilizado para obtener propiedades de la clase.
   */
  public BaseDao(SessionFactory factory, Class<T> entityClass) {
    Annotation entityAnnotation = entityClass.getAnnotation(Entity.class);
    if (entityAnnotation == null) {
      throw new RuntimeException(
          "La clase " + entityClass.getName() + " debe estar anotada con @Entity");
    }

    Table tableAnnotation = entityClass.getAnnotation(Table.class);
    if (tableAnnotation != null) {
      this.TABLE_NAME = tableAnnotation.name();
    } else {
      this.TABLE_NAME = entityClass.getName();
    }

    this.HQL_TABLE_NAME = entityClass.getName();
    this.SESSION = factory.openSession();
  }

  /**
   * Devuelve el nombre de la tabla de base de datos.
   * 
   * @return Table Name.
   */
  public String getTableName() {
    return this.TABLE_NAME;
  }

  /**
   * Devuelve el nombre de la tabla para consultas HQL.
   * 
   * @return Table Name.
   */
  public String getHqlTableName() {
    return this.HQL_TABLE_NAME;
  }

  /**
   * Obtiene la session para la creación de nuevos metodos en las clases hijas.
   * 
   * @return Session
   */
  protected Session getSession() {
    return this.SESSION;
  }

  /**
   * Devuelve un unico elemento de base de datos, utilizando el id de la tabla.
   * 
   * @param id
   * @return Una instancia de <T> o null.
   */
  public T get(ID id) {
    Query<T> query = this.SESSION.createQuery(" From " + this.HQL_TABLE_NAME + " where Id = :id");
    query.setParameter("id", id);
    return query.getSingleResult();
  }

  /**
   * Obtiene todos los registros de una base de datos.
   * 
   * @return una lista de elementos <T> o una lista vacia.
   */
  public List<T> getAll() {
    Query<T> query = this.SESSION.createQuery(" From " + this.HQL_TABLE_NAME);
    return query.getResultList();
  }

  /**
   * Inserta o actualiza un registro en la base de datos.
   * 
   * @param entity La entidad a actualizar o insertar.
   */
  public void save(T entity) {
    Transaction transaction = this.SESSION.beginTransaction();
    try {
      this.SESSION.saveOrUpdate(entity);
      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      throw e;
    }
  }

  /**
   * Guarda una lista de elementos en la base de datos.
   * 
   * @param entities La lista de elementos a guardar.
   */
  public void saveAll(List<T> entities) {
    Transaction transaction = this.SESSION.beginTransaction();
    try {
      for (var entity : entities) {
        this.SESSION.persist(entity);
      }
      this.SESSION.flush();
      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      throw e;
    }
  }

  /**
   * Elimina un registro de la base de datos.
   * 
   * @param entity Entidad a ser eliminada.
   */
  public void remove(T entity) {
    Transaction transaction = this.SESSION.beginTransaction();
    try {
      this.SESSION.remove(entity);
      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      throw e;
    }
  }

  /**
   * Elimina todos los registros de la tabla en la base de datos.
   */
  public void removeAll() {
    Transaction transaction = this.SESSION.beginTransaction();
    try {
      this.SESSION.createQuery("delete " + this.TABLE_NAME).executeUpdate();
      transaction.commit();
    } catch (Exception exception) {
      transaction.rollback();
      throw exception;
    }
  }

  @Override
  public void close() {
    this.SESSION.close();
  }

}

Y su implementación es la siguiente:

public class CuentaDao extends BaseDao<Cuenta, Integer> {

  public CuentaDao(SessionFactory factory) {
    super(factory, Cuenta.class);
  }

}

@berroteran
Copy link
Member

@jselvamadrigal entiedo.
ok, eso que me esta mostrando es lo mismo que GenericDAO , yo aun no lo he agregado, pero tengo este código,

veo que el confllicto seria el nombre.

`
package com.miProyecto.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.PersistenceContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;

public class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {

private final static Logger LOGGER = Logger.getLogger(GenericDAOImpl.class.getName());

SessionFactory sessionFactory;

@PersistenceContext
private Class<T> persistentClass;

@SuppressWarnings("unchecked")
public GenericDAOImpl() throws Exception {
	try {
		sessionFactory = HibernateUtil.getSessionFactory();
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
				.getActualTypeArguments()[0];
	} catch (final Exception e) {
		e.printStackTrace();
		throw e;
	}

}

/**
 * Runtime
 *
 */
@Override
public int count() throws BussinessException {
	final Session session = sessionFactory.getCurrentSession();
	try {
		session.beginTransaction();

		final Query query = session.createQuery("SELECT count(*) FROM " + getEntityClass().getName() + " e");
		final List<T> entities = query.list();
		// query.uni
		return ((Number) session.createCriteria(getEntityClass().getName()).setProjection(Projections.rowCount())
				.uniqueResult()).intValue();

	} catch (final javax.validation.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);

	} catch (final org.hibernate.exception.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);

	} catch (final RuntimeException ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(ex);

	} catch (final Exception ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(ex);
		
	} finally {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Falló al cerrar la sesion", exc);
		}
	}
}

@Override
/**
 * Metodo create instancia
 */
public T createInstance() throws BussinessException {
	try {
		return getEntityClass().newInstance();
	} catch (InstantiationException | IllegalAccessException ex) {
		throw new RuntimeException(ex);
	} catch (final RuntimeException ex) {
		throw ex;
	} catch (final Exception ex) {
		throw new RuntimeException(ex);
	}
}

@Override
public void delete(ID id) throws BussinessException {
	final Session session = sessionFactory.getCurrentSession();
	try {
		session.beginTransaction();
		final T entity = session.get(getEntityClass(), id);
		if (entity == null) {
			throw new BussinessException(new BussinessMessage(null, "Los datos a borrar ya no existen"));
		}
		session.delete(entity);
		session.getTransaction().commit();
	} catch (final javax.validation.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);
	} catch (final org.hibernate.exception.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);
	} catch (final BussinessException ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw ex;
	} catch (final RuntimeException ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw ex;
	} catch (final Exception ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new RuntimeException(ex);
	} finally {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Falló al cerrar la sesion", exc);
		}
	}
}

@Override
/**
 * Method Find
 */
public T finById(ID id) throws BussinessException {
	final Session session = sessionFactory.getCurrentSession();
	try {
		session.beginTransaction();
		final T entity = session.get(getEntityClass(), id);
		session.getTransaction().commit();

		return entity;
	} catch (final javax.validation.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);
	} catch (final org.hibernate.exception.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);
	} catch (final RuntimeException ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw ex;
	} catch (final Exception ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new RuntimeException(ex);
	} finally {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Falló al cerrar la sesion", exc);
		}
	}
}

@Override
public Collection<T> findAll() throws BussinessException {
	final Session session = sessionFactory.getCurrentSession();
	try {
		session.beginTransaction();

		final Query query = session.createQuery("SELECT e FROM " + getEntityClass().getName() + " e");
		final List<T> entities = query.list();

		return entities;

	} catch (final javax.validation.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);

	} catch (final org.hibernate.exception.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);

	} catch (final RuntimeException ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw ex;

	} catch (final Exception ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new RuntimeException(ex);
	} finally {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Falló al cerrar la sesion", exc);
		}
	}

}

private Class<T> getEntityClass() {
	return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}

@Override
public T saveOrUpdate(T entity) throws BussinessException {
	final Session session = sessionFactory.getCurrentSession();
	try {
		session.beginTransaction();

		// validando
		final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		final javax.validation.Validator validator = factory.getValidator();

		final Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);

		if (constraintViolations.size() > 0) {
			System.out.println("Constraint Violations occurred..");
			for (final ConstraintViolation<T> contraints : constraintViolations) {
				System.out.println(contraints.getRootBeanClass().getSimpleName() + "."
						+ contraints.getPropertyPath() + " " + contraints.getMessage());
			}
		}
		session.saveOrUpdate(entity);
		session.getTransaction().commit();

	} catch (final javax.validation.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw new BussinessException(cve);

	} catch (final org.hibernate.exception.ConstraintViolationException cve) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback.", exc);
		}
		throw new BussinessException(cve);

	} catch (final RuntimeException ex) {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
		throw ex;

	} catch (final Exception ex) {

		ex.printStackTrace();
		throw new RuntimeException(ex);
	} finally {
		try {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		} catch (final Exception exc) {
			LOGGER.log(Level.WARNING, "Failed to rollback", exc);
		}
	}
	return entity;
}

}

`

@jselvamadrigal
Copy link
Collaborator Author

@berroteran algo que no comprendo en su código es el por que la segmentación de las catch exception si todos incluyendo el catch Exception realiza lo mismo en su cuerpo, ya que existe un finally que completa lo que hacen los demás catch.

@luchonetvv luchonetvv changed the title 47 [TASK] - Crear clase BaseDao [TASK] - Crear clase BaseDao Jun 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
task Indica la necesidad de mejoras específicas que son más pequeñas
Projects
None yet
Development

No branches or pull requests

2 participants