Example usage for org.hibernate.criterion Projections projectionList

List of usage examples for org.hibernate.criterion Projections projectionList

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections projectionList.

Prototype

public static ProjectionList projectionList() 

Source Link

Document

Create a new projection list.

Usage

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

/**
 * A distinct projection that takes a list
 *
 * @param propertyNames The list of distince property names
 * @param alias The alias to use//  www  .j  a  v  a 2 s  .c o  m
 */
@SuppressWarnings("rawtypes")
public org.grails.datastore.mapping.query.api.Projections distinct(Collection propertyNames, String alias) {
    ProjectionList list = Projections.projectionList();
    for (Object o : propertyNames) {
        list.add(Projections.property(calculatePropertyName(o.toString())));
    }
    final Projection proj = Projections.distinct(list);
    addProjectionToList(proj, alias);
    return this;
}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/*  w  w  w . j  a  v a  2  s  .  com*/
public Object invokeMethod(String name, Object obj) {
    Object[] args = obj.getClass().isArray() ? (Object[]) obj : new Object[] { obj };

    if (paginationEnabledList && SET_RESULT_TRANSFORMER_CALL.equals(name) && args.length == 1
            && args[0] instanceof ResultTransformer) {
        resultTransformer = (ResultTransformer) args[0];
        return null;
    }

    if (isCriteriaConstructionMethod(name, args)) {
        if (criteria != null) {
            throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here"));
        }

        if (name.equals(GET_CALL)) {
            uniqueResult = true;
        } else if (name.equals(SCROLL_CALL)) {
            scroll = true;
        } else if (name.equals(COUNT_CALL)) {
            count = true;
        } else if (name.equals(LIST_DISTINCT_CALL)) {
            resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
        }

        createCriteriaInstance();

        // Check for pagination params
        if (name.equals(LIST_CALL) && args.length == 2) {
            paginationEnabledList = true;
            orderEntries = new ArrayList<Order>();
            invokeClosureNode(args[1]);
        } else {
            invokeClosureNode(args[0]);
        }

        if (resultTransformer != null) {
            criteria.setResultTransformer(resultTransformer);
        }
        Object result;
        if (!uniqueResult) {
            if (scroll) {
                result = criteria.scroll();
            } else if (count) {
                criteria.setProjection(Projections.rowCount());
                result = criteria.uniqueResult();
            } else if (paginationEnabledList) {
                // Calculate how many results there are in total. This has been
                // moved to before the 'list()' invocation to avoid any "ORDER
                // BY" clause added by 'populateArgumentsForCriteria()', otherwise
                // an exception is thrown for non-string sort fields (GRAILS-2690).
                criteria.setFirstResult(0);
                criteria.setMaxResults(Integer.MAX_VALUE);
                criteria.setProjection(Projections.rowCount());
                int totalCount = ((Number) criteria.uniqueResult()).intValue();

                // Restore the previous projection, add settings for the pagination parameters,
                // and then execute the query.
                if (projectionList != null && projectionList.getLength() > 0) {
                    criteria.setProjection(projectionList);
                } else {
                    criteria.setProjection(null);
                }
                for (Order orderEntry : orderEntries) {
                    criteria.addOrder(orderEntry);
                }
                if (resultTransformer == null) {
                    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
                } else if (paginationEnabledList) {
                    // relevant to GRAILS-5692
                    criteria.setResultTransformer(resultTransformer);
                }
                // GRAILS-7324 look if we already have association to sort by
                Map argMap = (Map) args[0];
                final String sort = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_SORT);
                if (sort != null) {
                    boolean ignoreCase = true;
                    Object caseArg = argMap.get(GrailsHibernateUtil.ARGUMENT_IGNORE_CASE);
                    if (caseArg instanceof Boolean) {
                        ignoreCase = (Boolean) caseArg;
                    }
                    final String orderParam = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_ORDER);
                    final String order = GrailsHibernateUtil.ORDER_DESC.equalsIgnoreCase(orderParam)
                            ? GrailsHibernateUtil.ORDER_DESC
                            : GrailsHibernateUtil.ORDER_ASC;
                    int lastPropertyPos = sort.lastIndexOf('.');
                    String associationForOrdering = lastPropertyPos >= 0 ? sort.substring(0, lastPropertyPos)
                            : null;
                    if (associationForOrdering != null && aliasMap.containsKey(associationForOrdering)) {
                        addOrder(criteria, aliasMap.get(associationForOrdering) + "."
                                + sort.substring(lastPropertyPos + 1), order, ignoreCase);
                        // remove sort from arguments map to exclude from default processing.
                        @SuppressWarnings("unchecked")
                        Map argMap2 = new HashMap(argMap);
                        argMap2.remove(GrailsHibernateUtil.ARGUMENT_SORT);
                        argMap = argMap2;
                    }
                }
                GrailsHibernateUtil.populateArgumentsForCriteria(grailsApplication, targetClass, criteria,
                        argMap);
                PagedResultList pagedRes = new PagedResultList(criteria.list());

                // Updated the paged results with the total number of records calculated previously.
                pagedRes.setTotalCount(totalCount);
                result = pagedRes;
            } else {
                result = criteria.list();
            }
        } else {
            result = GrailsHibernateUtil.unwrapIfProxy(criteria.uniqueResult());
        }
        if (!participate) {
            hibernateSession.close();
        }
        return result;
    }

    if (criteria == null)
        createCriteriaInstance();

    MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
    if (metaMethod != null) {
        return metaMethod.invoke(this, args);
    }

    metaMethod = criteriaMetaClass.getMetaMethod(name, args);
    if (metaMethod != null) {
        return metaMethod.invoke(criteria, args);
    }
    metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
    if (metaMethod != null) {
        return metaMethod.invoke(criteria, args);
    }

    if (isAssociationQueryMethod(args) || isAssociationQueryWithJoinSpecificationMethod(args)) {
        final boolean hasMoreThanOneArg = args.length > 1;
        Object callable = hasMoreThanOneArg ? args[1] : args[0];
        int joinType = hasMoreThanOneArg ? (Integer) args[0] : CriteriaSpecification.INNER_JOIN;

        if (name.equals(AND) || name.equals(OR) || name.equals(NOT)) {
            if (criteria == null) {
                throwRuntimeException(
                        new IllegalArgumentException("call to [" + name + "] not supported here"));
            }

            logicalExpressionStack.add(new LogicalExpression(name));
            invokeClosureNode(callable);

            LogicalExpression logicalExpression = logicalExpressionStack
                    .remove(logicalExpressionStack.size() - 1);
            addToCriteria(logicalExpression.toCriterion());

            return name;
        }

        if (name.equals(PROJECTIONS) && args.length == 1 && (args[0] instanceof Closure)) {
            if (criteria == null) {
                throwRuntimeException(
                        new IllegalArgumentException("call to [" + name + "] not supported here"));
            }

            projectionList = Projections.projectionList();
            invokeClosureNode(callable);

            if (projectionList != null && projectionList.getLength() > 0) {
                criteria.setProjection(projectionList);
            }

            return name;
        }

        final PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(targetClass, name);
        if (pd != null && pd.getReadMethod() != null) {
            ClassMetadata meta = sessionFactory.getClassMetadata(targetClass);
            Type type = meta.getPropertyType(name);
            if (type.isAssociationType()) {
                String otherSideEntityName = ((AssociationType) type)
                        .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
                Class oldTargetClass = targetClass;
                targetClass = sessionFactory.getClassMetadata(otherSideEntityName)
                        .getMappedClass(EntityMode.POJO);
                if (targetClass.equals(oldTargetClass) && !hasMoreThanOneArg) {
                    joinType = CriteriaSpecification.LEFT_JOIN; // default to left join if joining on the same table
                }
                associationStack.add(name);
                final String associationPath = getAssociationPath();
                createAliasIfNeccessary(name, associationPath, joinType);
                // the criteria within an association node are grouped with an implicit AND
                logicalExpressionStack.add(new LogicalExpression(AND));
                invokeClosureNode(callable);
                aliasStack.remove(aliasStack.size() - 1);
                if (!aliasInstanceStack.isEmpty()) {
                    aliasInstanceStack.remove(aliasInstanceStack.size() - 1);
                }
                LogicalExpression logicalExpression = logicalExpressionStack
                        .remove(logicalExpressionStack.size() - 1);
                if (!logicalExpression.args.isEmpty()) {
                    addToCriteria(logicalExpression.toCriterion());
                }
                associationStack.remove(associationStack.size() - 1);
                targetClass = oldTargetClass;

                return name;
            }
        }
    } else if (args.length == 1 && args[0] != null) {
        if (criteria == null) {
            throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here"));
        }

        Object value = args[0];
        Criterion c = null;
        if (name.equals(ID_EQUALS)) {
            return eq("id", value);
        }

        if (name.equals(IS_NULL) || name.equals(IS_NOT_NULL) || name.equals(IS_EMPTY)
                || name.equals(IS_NOT_EMPTY)) {
            if (!(value instanceof String)) {
                throwRuntimeException(new IllegalArgumentException(
                        "call to [" + name + "] with value [" + value + "] requires a String value."));
            }
            String propertyName = calculatePropertyName((String) value);
            if (name.equals(IS_NULL)) {
                c = Restrictions.isNull(propertyName);
            } else if (name.equals(IS_NOT_NULL)) {
                c = Restrictions.isNotNull(propertyName);
            } else if (name.equals(IS_EMPTY)) {
                c = Restrictions.isEmpty(propertyName);
            } else if (name.equals(IS_NOT_EMPTY)) {
                c = Restrictions.isNotEmpty(propertyName);
            }
        }

        if (c != null) {
            return addToCriteria(c);
        }
    }

    throw new MissingMethodException(name, getClass(), args);
}

From source file:id.co.sambaltomat.core.dao.hibernate.GenericDaoHibernate.java

/**
 * Select specific column names/*from w w  w . j  a  va 2 s.c  o m*/
 *
 * @param id primary key
 * @param columnNames argumen dinamis, sebutkan nama2 column string yang di pilih dalam SELECT
 * @return
 */
public T get(final PK id, final String... columnNames) {
    return (T) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = session.createCriteria(persistentClass, "talias");
            criteria.add(Restrictions.idEq(id));
            ProjectionList projectionList = Projections.projectionList();
            for (String columnName : columnNames) {
                projectionList.add(Projections.property("talias." + columnName), columnName);
            }
            criteria.setProjection(projectionList);
            criteria.setResultTransformer(new AliasToBeanResultTransformer(persistentClass));
            Object returnObject = criteria.uniqueResult();
            return returnObject;
        }
    });
}

From source file:id.co.sambaltomat.core.dao.hibernate.GenericDaoHibernate.java

public int getRowCount(final List<Criterion> params, final List<JoinPath> joinPaths) {
    return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Integer count = Integer.valueOf("0");
            ProjectionList projectionList = Projections.projectionList();
            Criteria criteria = session.createCriteria(persistentClass);

            processJoinPath(criteria, joinPaths, projectionList);
            if (params != null) {
                for (Criterion criterion : params) {
                    criteria.add(criterion);
                }/*from w  w w .ja va2s  .  c  o m*/
            }
            //jika projectionList tidak kosong berarti ada GROUPING, lakukan konversi criteria
            if (projectionList.getLength() > 0) {
                criteria.setProjection(projectionList);
                String sql = criteriaToString(criteria);
                sql = "select count(*) from (" + sql + ") as countTemp";
                //native SQL dijalankan
                SQLQuery sqlQuery = session.createSQLQuery(sql);
                List result = sqlQuery.list();
                if (result != null && result.size() > 0) {
                    count = (Integer) result.get(0);
                }

            } else {
                criteria.setProjection(projectionList.add(Projections.rowCount()));
                List result = criteria.list();
                if (result != null && result.size() > 0) {
                    count = (Integer) result.get(0);
                }
            }
            return count;
        }
    });
}

From source file:id.co.sambaltomat.core.dao.hibernate.GenericDaoHibernate.java

protected void processJoinPath(Criteria criteria, List<JoinPath> joinPaths, ProjectionList projectionList) {
    boolean isDistinctRoot = true;
    if (joinPaths != null && !joinPaths.isEmpty()) {
        for (JoinPath joinPath : joinPaths) {
            if (joinPath.joinType == JoinType.INNER_JOIN)
                criteria.createCriteria(joinPath.path, joinPath.alias, CriteriaSpecification.INNER_JOIN);
            else if (joinPath.joinType == JoinType.LEFT_JOIN)
                criteria.createCriteria(joinPath.path, joinPath.alias, CriteriaSpecification.LEFT_JOIN);
            else if (joinPath.joinType == JoinType.NON_DISTINCT_ROOT_ENTITY)
                isDistinctRoot = false;//from   w  w  w  .  j a va2 s .com
            else if (joinPath.joinType == JoinType.GROUPING_FIELD) {
                if (projectionList == null) {
                    projectionList = Projections.projectionList();
                }
                projectionList.add(Projections.groupProperty(joinPath.alias));
            } else
                criteria.setFetchMode(joinPath.path, FetchMode.SELECT);

        }
    }
    if (isDistinctRoot)
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}

From source file:info.interactivesystems.spade.dao.ReviewDao.java

License:Apache License

@SuppressWarnings("unchecked")
public List<Review> findReviewsByCategory(String category) {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Review.class, "review");

    criteria.createAlias("review.product", "product");
    criteria.add(Restrictions.eq("product.category", category));
    criteria.add(Restrictions.eq("unique", true));

    criteria.setProjection(Projections.projectionList().add(Projections.property("id"), "id")
            .add(Projections.property("nilsimsa"), "nilsimsa"))
            .setResultTransformer(Transformers.aliasToBean(Review.class));

    return criteria.list();
}

From source file:info.interactivesystems.spade.dao.ReviewDao.java

License:Apache License

@SuppressWarnings("unchecked")
public List<Review> findReviewFromUserInCategory(String userID, String category) {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Review.class, "review");

    criteria.createAlias("review.product", "product");
    criteria.add(Restrictions.eq("product.category", category));
    criteria.add(Restrictions.eq("user.id", userID));
    criteria.add(Restrictions.eq("unique", true));

    criteria.setProjection(Projections.projectionList().add(Projections.property("id"), "id")
            .add(Projections.property("nilsimsa"), "nilsimsa"))
            .setResultTransformer(Transformers.aliasToBean(Review.class));

    return criteria.list();
}

From source file:interfaces.Alta.java

private int maxIdCliente() {
    Session session;/*  w  ww.  j a  v  a  2s  .c  om*/
    session = ConexionUtil.getSessionFactory().openSession();
    Criteria criteria = session.createCriteria(Cliente.class);
    criteria.add(Restrictions.isNotNull("idCliente"));
    criteria.setProjection(Projections.projectionList().add(Projections.max("idCliente")));

    if (criteria.list().get(0) != null) {
        return (int) criteria.list().get(0) + 1;
    } else
        return 1;
}

From source file:inventory.executors.CommonTasks.java

public static void fillComboboxByClientList(ComboBox clientCombo) {
    try {//www .ja v a 2s.  co  m
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria clientNameCriteria = session.createCriteria(ClientTable.class);
        clientNameCriteria.setProjection(Projections.projectionList().add(Projections.property("clientName")));
        ArrayList<ClientTable> clientNameList = (ArrayList<ClientTable>) clientNameCriteria.list();
        Iterator<ClientTable> clientItr = clientNameList.iterator();

        if (clientItr.hasNext()) {
            clientCombo.setTooltip(new Tooltip());
            if (clientCombo != null) {
                clientCombo.getItems().removeAll();
            }
            while (clientItr.hasNext()) {
                clientCombo.getItems().add("" + clientItr.next());
            }
            // Enabling AutoComplete Text
            //                AutoTextCompletionJComboBox.enable(clientCombo);
        }
        //        } catch (IllegalArgumentException iae) {
        //            fillComboboxByClientList(clientCombo);
        //            iae.printStackTrace();
    } catch (IllegalArgumentException iae) {
        fillComboBoxByItemList(clientCombo);
        iae.printStackTrace();
    } catch (HibernateException ex) {
        ex.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session.isOpen()) {
            session.close();
        }
    }
}

From source file:inventory.executors.CommonTasks.java

public static void fillComboBoxByItemList(ComboBox itemCombo) {
    try {//from   w  w w.ja v  a 2  s . co  m
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria itemNameCriteria = session.createCriteria(ItemTable.class);
        itemNameCriteria.setProjection(Projections.projectionList().add(Projections.property("itemName")));
        ArrayList<ItemTable> itemNameList = (ArrayList<ItemTable>) itemNameCriteria.list();
        Iterator<ItemTable> itemItr = itemNameList.iterator();

        if (itemItr.hasNext()) {
            itemCombo.setTooltip(new Tooltip());
            if (itemCombo != null) {
                itemCombo.getItems().removeAll();
            }
            while (itemItr.hasNext()) {
                itemCombo.getItems().add("" + itemItr.next());
            }
            // Enabling AutoComplete Text
            //                AutoTextCompletionJComboBox.enable(itemCombo);
        }
    } catch (IllegalArgumentException iae) {
        fillComboBoxByItemList(itemCombo);
        iae.printStackTrace();
    } catch (HibernateException ex) {
        ex.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session.isOpen()) {
            session.close();
        }
    }
}