net.przemkovv.sphinx.dao.impl.DefaultGenericDAO.java Source code

Java tutorial

Introduction

Here is the source code for net.przemkovv.sphinx.dao.impl.DefaultGenericDAO.java

Source

/*
 * The MIT License
 *
 * Copyright 2012 Przemyslaw Walkowiak <przemyslaw.walkowiak@put.poznan.pl>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package net.przemkovv.sphinx.dao.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import net.przemkovv.sphinx.dao.GenericDAO;
import net.przemkovv.sphinx.model.ModelObject;
import org.hibernate.FetchMode;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Przemyslaw Walkowiak <przemyslaw.walkowiak@put.poznan.pl>
 * @param <T>
 */
public class DefaultGenericDAO<T extends ModelObject> implements GenericDAO<T> {

    private final Class<T> type;
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DefaultGenericDAO.class);

    @PersistenceContext
    EntityManager em;

    private SessionFactory sessionFactory;

    public Session getCurrentSession() {
        return em.unwrap(Session.class);
    }

    public EntityManager getEntityManager() {
        return em;
    }

    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    public DefaultGenericDAO(Class<T> type) {
        super();
        this.type = type;
    }

    @Transactional(readOnly = true)
    @Override
    public T getById(Long id) {
        if (id == null) {
            return null;
        } else {
            return (T) getEntityManager().find(type, id);
        }
    }

    @Override
    public <T extends Object> T getById(Long id, String[] collectionsToBeInitialized) {
        T entity = (T) getCurrentSession().createCriteria(type).add(Restrictions.idEq(id))
                .setFetchMode(collectionsToBeInitialized[0], FetchMode.JOIN).uniqueResult();
        int length = collectionsToBeInitialized.length;
        for (int idx = 1; idx < length; idx++) {
            String collectionName = collectionsToBeInitialized[idx];
            try {
                Method m = type.getMethod(
                        "get" + collectionName.substring(0, 1).toUpperCase() + collectionName.substring(1));
                Hibernate.initialize(m.invoke(entity, (Object[]) null));
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                logger.error("Could not initialize collection " + collectionName + " of class Event", e);
            }
        }
        return entity;
    }

    @Transactional(readOnly = true)
    @Override
    public List<T> getAll() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<T> cq = cb.createQuery(type);
        cq.from(type);
        return em.createQuery(cq).getResultList();
    }

    @Override
    public void save(T object) {
        logger.debug("Inserting {}", object.toString());
        getEntityManager().persist(object);
    }

    @Override
    public T update(T object) {
        return em.merge(object);
    }

    @Override
    public T saveOrUpdate(T object) {
        return em.merge(object);
    }

    @Override
    public void delete(T object) {
        object = em.merge(object);
        em.remove(object);
    }

    @Override
    public void delete(Long id) {
        T obj = em.getReference(type, id);
        em.remove(obj);
    }

    @Override
    public List<T> findByCriteria(DetachedCriteria criteria) {
        return criteria.getExecutableCriteria(getCurrentSession()).list();
    }

    @Override
    public <E> List<E> findByCriteriaProjection(DetachedCriteria criteria) {
        return criteria.getExecutableCriteria(getCurrentSession()).list();
    }

    @Override
    public T getByCriteria(DetachedCriteria criteria) {
        return (T) criteria.getExecutableCriteria(getCurrentSession()).uniqueResult();
    }

    @Override
    public List<T> findByCriteria(Integer first, Integer pageSize, DetachedCriteria criteria) {
        return criteria.getExecutableCriteria(getCurrentSession()).setFirstResult(first).setMaxResults(pageSize)
                .list();
    }

    @Override
    public Long countByCriteria(DetachedCriteria criteria) {
        return (Long) criteria.getExecutableCriteria(getCurrentSession()).setProjection(Projections.rowCount())
                .uniqueResult();
    }

    @Override
    public Long countAll() {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Long> cq = cb.createQuery(Long.class);
        cq.select(cb.count(cq.from(type)));
        return getEntityManager().createQuery(cq).getSingleResult();
    }
}