All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ec.gob.senescyt.sniese.commons.dao.AbstractServicioDAO Maven / Gradle / Ivy

There is a newer version: 2.0.5
Show newest version
package ec.gob.senescyt.sniese.commons.dao;

import com.google.common.annotations.VisibleForTesting;
import ec.gob.senescyt.sniese.commons.core.EntidadBase;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;

import javax.persistence.Table;
import java.io.Serializable;
import java.util.List;

public abstract class AbstractServicioDAO extends AbstractDAO {
    protected String nombreTabla = getEntityClass().getAnnotation(Table.class).name();

    protected String defaultSchema;

    public AbstractServicioDAO(SessionFactory sessionFactory, String defaultSchema) {
        super(sessionFactory);
        this.defaultSchema = defaultSchema;
    }

    public T guardar(T entidad) {
        return persist(entidad);
    }
    public T actualizar(T entidad) {
        return (T) currentSession().merge(entidad);
    }

    public T obtenerPorId(Serializable id) {
        return get(id);
    }

    @VisibleForTesting
    public void limpiar() {
        String sqlQuery = String.format("TRUNCATE %s.%s CASCADE", defaultSchema, nombreTabla);
        Query query = currentSession().createSQLQuery(sqlQuery);
        query.executeUpdate();
    }

    public List obtenerTodos() {
        return obtenerCriteria()
                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
    }

    public T obtenerEntidadConRestriccion(SimpleExpression restriction) {
        Criteria criteria = obtenerCriteria();
        return (T) criteria.add(restriction).uniqueResult();
    }

    protected Criteria obtenerCriteria() {
        return currentSession().createCriteria(getEntityClass());
    }

    public void eliminar(Serializable id) {
        T registro = (T) currentSession().load(getEntityClass(), id);
        currentSession().delete(registro);
    }

    public String nombreDeLaColeccion() {
        return nombreTabla;
    }

    public List encontrarPorIds(List ids) {
        return obtenerCriteria().add(Restrictions.in("id", ids)).list();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy