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

net.leanix.dropkit.persistence.BaseDAO Maven / Gradle / Ivy

There is a newer version: 2.0.5
Show newest version
package net.leanix.dropkit.persistence;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import io.dropwizard.hibernate.AbstractDAO;
import java.util.ArrayList;
import java.util.Iterator;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.hibernate.Criteria;
import org.hibernate.NullPrecedence;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.internal.CriteriaImpl.Subcriteria;

/**
 * BaseDAO
 *
 * @param  the entity type
 */
public class BaseDAO extends AbstractDAO {

    public BaseDAO(SessionFactory factory) {
        super(factory);
    }

    /**
     * Returns the count based on the given criteria.
     *
     * @param criteria conditions to meet
     * @return
     * @deprecated
     */
    public Long count(Criteria criteria) {
        criteria.setProjection(Projections.rowCount());
        return (Long) criteria.uniqueResult();
    }

    /**
     * Generic find method that uses criteria and supports pagination and ordering.
     *
     * @param pageRequest request for paging
     * @param criteria hibernate criteria api restrictions for query
     * @return
     */
    @SuppressWarnings("unchecked")
    public PageResult find(AbstractPageRequest pageRequest, Criteria criteria) {
        PageResult pageResult = new PageResult<>();

        // Get count
        pageResult.setTotal(count(criteria));

        // Get list
        criteria.setProjection(null);
        criteria.setResultTransformer(Criteria.ROOT_ENTITY);
        Criteria curCriteria = this.createCriteria(pageRequest, criteria);
        pageResult.setPageRequest(pageRequest);
        pageResult.setData(curCriteria.list());

        return pageResult;
    }

    /**
     * Generic find method that uses criteria and supports pagination and ordering.
     *
     * @param pageRequest request for paging
     * @return
     */
    public PageResult find(PageRequest pageRequest) {
        return this.find(pageRequest, this.createCriteria());
    }

    /**
     * Returns a query-ready hibernate criteria.
     *
     * @return query-ready hibernate criteria
     * @deprecated use {@linkplain #createCriteriaQuery()} instead.
     */
    public Criteria createCriteria() {
        return criteria();
    }

    /**
     * Returns a query-ready hibernate criteria. Includes pagination, sorting and restrictions.
     *
     * @param pageRequest request for paging
     * @param criteria hibernate criteria restrictions for query
     * @return query-ready hibernate criteria
     */
    public Criteria createCriteria(AbstractPageRequest pageRequest, Criteria criteria) {
        // set ordering
        if (pageRequest.hasSort()) {
            for (String stringOrder : pageRequest.getSort().split(",")) {
                addOrder(criteria, stringOrder, pageRequest.getNullPrecedence());
            }
        }

        if (pageRequest.computeOffset() != null && pageRequest.getSize() > 0) {
            criteria.setFirstResult(pageRequest.computeOffset());
            criteria.setMaxResults(pageRequest.getSize());
        }

        return criteria;
    }

    /**
     * Handles the sort order.
     *
     * @param criteria
     * @param stringOrder
     * @link http://stackoverflow.com/questions/870029/hibernate-order-by-association
     */
    private void addOrder(Criteria criteria, String stringOrder, NullPrecedence nullPrecedence) {
        String direction = stringOrder.toLowerCase().endsWith("desc") ? "desc" : "asc";

        String sortProp = stringOrder.replaceAll("(?i)-" + direction, "");

        // we need to introduce an alias for relations
        if (sortProp.contains(".")) {
            ArrayList parts = Lists.newArrayList(Splitter.on('.').trimResults().omitEmptyStrings().split(sortProp));
            if (parts.size() == 1) {
                return;
            }

            createAliasIfNotAlreadyExist(criteria, parts.get(0), parts.get(0));
        }

        if ("asc".equals(direction)) {
            criteria.addOrder(Order.asc(sortProp).nulls(nullPrecedence));
        } else {
            criteria.addOrder(Order.desc(sortProp).nulls(nullPrecedence));
        }
    }

    /**
     *
     * @link http://taghjijtopentech.blogspot.de/2013/09/hibernate-criteria-duplicate-alias-and.html
     *
     * @param criteria
     * @param associationPath
     * @param newAlias
     * @return
     */
    private String createAliasIfNotAlreadyExist(Criteria criteria, String associationPath, String newAlias) {
        CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;

        Iterator it = criteriaImpl.iterateSubcriteria();
        boolean aliasAlreadyExists = false;
        String alias = null;
        while (it.hasNext()) {
            Subcriteria subCriteria = it.next();
            if (associationPath.equals(subCriteria.getPath())) {// identifie la jointure sur l'objet
                aliasAlreadyExists = true;
                alias = subCriteria.getAlias();// l'alias
                // System.out.println("associationPath : '" + associationPath+"' already exist with alias = '" + alias+"'");
                break;
            }
        }
        if (!aliasAlreadyExists) {
            // System.out.println("associationPath : '"+associationPath+"' doesn't exists ");
            criteria.createAlias(associationPath, newAlias);
            alias = newAlias;
            // System.out.println("new one is created");
        }
        return alias;
    }

    /**
     * Returns a query-ready hibernate criteria. Includes pagination, sorting and restrictions.
     *
     * @param pageRequest
     * @return
     */
    public Criteria createCriteria(PageRequest pageRequest) {
        return this.createCriteria(pageRequest, criteria());
    }

    /*
     * ******************** Hibernate 5.2 stuff ***************
     */

    public CriteriaBuilder getCriteriaBuilder() {
        CriteriaBuilder criteriaBuilder = currentSession().getCriteriaBuilder();
        return criteriaBuilder;
    }

    /**
     * Provides a new {@linkplain CriteriaQuery} for the current session. This method replaces the old
     * {@linkplain #createCriteria()} method which provides a {@link Criteria} objects that is deprecated since hibernate 5.2.
     * 
     * @return
     */
    public CriteriaQuery createCriteriaQuery() {
        CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
        CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(getEntityClass());
        return criteriaQuery;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy