Example usage for javax.persistence.criteria CriteriaQuery distinct

List of usage examples for javax.persistence.criteria CriteriaQuery distinct

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery distinct.

Prototype

CriteriaQuery<T> distinct(boolean distinct);

Source Link

Document

Specify whether duplicate query results will be eliminated.

Usage

From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java

/**
 * @see ??JPA/*ww w. ja  v a  2s . com*/
 * @param filters
 * @param entityClazz
 * @param isDistinct  trueSQLdistinctfalse?
 * @return
 */
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) {
    return new Specification<T>() {
        @Override
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (orderParams != null && orderParams.size() > 0) {
                /*
                CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
                Root<Foo> from = criteriaQuery.from(Foo.class);
                CriteriaQuery<Foo> select = criteriaQuery.select(from);
                criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
                */
                List<Order> orders = new ArrayList<Order>(orderParams.size());
                for (OrderParam orderParam : orderParams) {
                    if (orderParam != null && orderParam.getField() != null) {
                        String fields[] = StringUtil.split(orderParam.getField(), '.');
                        Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]);
                        for (int i = 1, len = fields.length; i < len; ++i) {
                            expression = expression.get(fields[i]);
                        }
                        if (expression != null) {
                            Order order = (orderParam.getType() == null
                                    || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression)
                                            : builder.desc(expression);
                            orders.add(order);
                            //                        query.orderBy(order);
                        }
                    }
                }
                query.orderBy(orders);
            }
            query.distinct(isDistinct);
            if (Collections3.isNotEmpty(filters)) {
                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName, ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, '.');
                    Path expression = null;

                    //////  ?
                    boolean hasJoin = names[0].startsWith("[join]");
                    String fn = hasJoin ? names[0].substring(6) : names[0];
                    boolean isNotDateType = !(filter.value instanceof Date);
                    try {
                        expression = hasJoin ? root.join(fn) : root.get(fn);
                        if (isNotDateType && isDateType(expression.getJavaType())) {
                            // filter.value??
                            filter.value = parseDate(filter.value.toString(), filter.operator);
                        }
                    } catch (Exception e) {
                        //                     logger.error(e.getMessage(), e);
                        continue; // ??
                    }
                    boolean isPropertyNotValid = false;
                    for (int i = 1; i < names.length; i++) {
                        try {
                            expression = expression.get(names[i]);
                            if (isNotDateType && isDateType(expression.getJavaType())) {
                                filter.value = parseDate(filter.value.toString(), filter.operator);
                            }
                        } catch (Exception e) {
                            //                        logger.error(e.getMessage(), e);
                            isPropertyNotValid = true; // 
                            break; // ??
                        }
                    }
                    if (expression == null || isPropertyNotValid) {
                        continue;
                    }
                    ///////

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case ORLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.or(like));
                        }

                        break;
                    case ANDLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case ANDNOTLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notLike(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case OREQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.equal(expression, values[i]);
                            }
                            predicates.add(builder.or(like));
                        }
                        break;

                    case ANDNOTEQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notEqual(expression, values[i]);
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case NOTEQ:
                        predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                        break;
                    case NOTLIKE:
                        predicates.add(builder.notLike(expression, "%" + filter.value + "%"));
                        break;
                    case NULL:
                        predicates.add(builder.isNull(expression));
                        break;
                    case NOTNULL:
                        predicates.add(builder.isNotNull(expression));
                        break;
                    //                  case IN:
                    //                     predicates.add(builder.in(expression).in(values));
                    //                     break;
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            return builder.conjunction();
        }
    };
}

From source file:org.verinice.persistence.CnaTreeElementDaoImpl.java

private TypedQuery<CnaTreeElement> createQueryForScopeKeyValue(Integer scopeId, String key, String value) {
    CriteriaQuery<CnaTreeElement> query = getCriteriaBuilder().createQuery(CnaTreeElement.class);
    Root<CnaTreeElement> rootelement = query.from(CnaTreeElement.class);
    query.select(rootelement);//w  ww .  j  a  v  a  2 s . com

    Join<CnaTreeElement, Entity> entityJoin = rootelement.join("entity", JoinType.LEFT);
    Join<PropertyList, Entity> propertyListJoin = entityJoin.join("propertyLists", JoinType.LEFT);
    Join<PropertyList, Property> propertyJoin = propertyListJoin.join("properties", JoinType.LEFT);

    List<Predicate> conditions = new ArrayList<>();
    if (key != null) {
        conditions.add(getCriteriaBuilder().like(propertyJoin.get("propertytype"), key));
    }
    if (value != null) {
        conditions.add(getCriteriaBuilder().like(propertyJoin.get("propertyvalue"), value));
    }
    if (scopeId != null) {
        conditions.add(getCriteriaBuilder().equal(rootelement.get("scopeId"), scopeId));
    }
    query.where(conditions.toArray(new Predicate[conditions.size()]));

    query.distinct(true);
    return entityManager.createQuery(query);
}

From source file:org.openmeetings.app.data.conference.Roommanagement.java

/**
 * gets a list of all availible rooms//from   w  ww .  j av a  2 s.  co  m
 * 
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @param asc
 * @return
 */
public List<Rooms> getRoomsInternatl(int start, int max, String orderby, boolean asc) {
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Rooms> cq = cb.createQuery(Rooms.class);
        Root<Rooms> c = cq.from(Rooms.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        cq.where(condition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<Rooms> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Rooms> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getRooms ] ", ex2);
    }
    return null;
}

From source file:org.openmeetings.app.data.conference.Roommanagement.java

public List<Rooms> getRoomsInternatlbyType(int start, int max, String orderby, boolean asc,
        String externalRoomType) {
    try {//from   w  w w.  j  ava2s  . com
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Rooms> cq = cb.createQuery(Rooms.class);
        Root<Rooms> c = cq.from(Rooms.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        Predicate subCondition = cb.equal(c.get("externalRoomType"), externalRoomType);
        cq.where(condition, subCondition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<Rooms> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Rooms> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getRooms ] ", ex2);
    }
    return null;
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

/**
 * query for a list of users/*  w  w w  .j  a  va2s .c o  m*/
 * 
 * @param users_id
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @return
 */
public SearchResult<Users> getUsersList(long user_level, int start, int max, String orderby, boolean asc) {
    try {
        if (authLevelManagement.checkAdminLevel(user_level)) {
            SearchResult<Users> sresult = new SearchResult<Users>();
            sresult.setObjectName(Users.class.getName());
            sresult.setRecords(usersDao.selectMaxFromUsers());

            // get all users
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Users> cq = cb.createQuery(Users.class);
            Root<Users> c = cq.from(Users.class);
            Predicate condition = cb.equal(c.get("deleted"), "false");
            cq.where(condition);
            cq.distinct(asc);
            if (asc) {
                cq.orderBy(cb.asc(c.get(orderby)));
            } else {
                cq.orderBy(cb.desc(c.get(orderby)));
            }
            TypedQuery<Users> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<Users> ll = q.getResultList();
            sresult.setResult(ll);
            return sresult;
        }
    } catch (Exception ex2) {
        log.error("[getUsersList] " + ex2);
    }
    return null;
}

From source file:de.hopmann.msc.slave.service.PackageInstallationBean.java

public PackageInstallationEntity getInstallationEntity(PackageResolved packageModel,
        Set<PackageInstallationEntity> requiredDependencies, PackageInstallerHolder packageInstallerHolder) {
    try {// w w  w. j a  v  a2s.com

        // TODO repository version, flavor, etc.

        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<PackageInstallationEntity> query = cb.createQuery(PackageInstallationEntity.class);
        Root<PackageInstallationEntity> p = query.from(PackageInstallationEntity.class);
        Path<PackageInstallerEntity> pInstaller = p.get(PackageInstallationEntity_.packageInstaller);

        List<Predicate> predicates = new ArrayList<Predicate>();

        predicates.add(cb.equal(p.get(PackageInstallationEntity_.packageName), packageModel.getPackageName()));
        predicates.add(cb.equal(p.get(PackageInstallationEntity_.sourceVersion).get(Version_.versionNumber),
                packageModel.getPackageAccessor().getSourceVersion().getVersionNumber()));

        predicates.add(cb.between(pInstaller.get(PackageInstallerEntity_.version).get(Version_.versionNumber),
                packageInstallerHolder.getDependencyMinVersion(),
                packageInstallerHolder.getDependencyMaxVersion()));

        // TODO flavor arch

        if (requiredDependencies.isEmpty()) {
            query.where(cb.and(predicates.toArray(new Predicate[] {})));
        } else {
            SetJoin<PackageInstallationEntity, PackageInstallationEntity> join = p
                    .join(PackageInstallationEntity_.actualDependencies);

            predicates.add(join.in(requiredDependencies));

            // Expression<Set<PackageInstallationEntity>> pDependencies = p
            // .get(PackageInstallationEntity_.actualDependencies);
            // predicates.add(pDependencies.in(requiredDependencies));

            query.where(cb.and(predicates.toArray(new Predicate[] {})));
            Path<Long> pId = p.get(PackageInstallationEntity_.id);
            query.groupBy(pId);
            query.having(cb.ge(cb.count(pId), requiredDependencies.size()));
            query.distinct(true);
        }

        return entityManager.createQuery(query).getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

/**
 * suche eines Bentzers//from  w w  w .  java2s. c om
 * 
 * @param user_level
 * @param searchstring
 * @param max
 * @param start
 * @return
 */
public List<Users> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start,
        String orderby, boolean asc) {
    if (authLevelManagement.checkAdminLevel(user_level)) {
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Users> cq = cb.createQuery(Users.class);
            Root<Users> c = cq.from(Users.class);
            Expression<String> literal = cb.literal("%" + searchstring + "%");
            // crit.add(Restrictions.ilike(searchcriteria, "%" +
            // searchstring + "%"));
            Path<String> path = c.get(searchcriteria);
            Predicate predicate = cb.like(path, literal);
            Predicate condition = cb.notEqual(c.get("deleted"), "true");
            cq.where(condition, predicate);
            cq.distinct(asc);
            if (asc) {
                cq.orderBy(cb.asc(c.get(orderby)));
            } else {
                cq.orderBy(cb.desc(c.get(orderby)));
            }
            TypedQuery<Users> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<Users> contactsZ = q.getResultList();
            return contactsZ;
        } catch (Exception ex2) {
            log.error("searchUser", ex2);
        }
    }
    return null;
}

From source file:org.agric.oxm.utils.JpaUtils.java

/**
 * Copy Criteria without Selection/*  w w w  . j a v  a 2  s . c o  m*/
 * 
 * @param from
 *            source Criteria
 * @param to
 *            destination Criteria
 */
public static void copyCriteriaNoSelection(CriteriaQuery<?> from, CriteriaQuery<?> to) {

    // Copy Roots
    for (Root<?> root : from.getRoots()) {
        Root<?> dest = to.from(root.getJavaType());
        dest.alias(getOrCreateAlias(root));
        copyJoins(root, dest);
    }

    to.groupBy(from.getGroupList());
    to.distinct(from.isDistinct());
    to.having(from.getGroupRestriction());
    to.where(from.getRestriction());
    to.orderBy(from.getOrderList());
}

From source file:org.apache.openmeetings.data.user.UserManager.java

/**
 * query for a list of users/*from  w  ww .  j a v  a2 s .c  o m*/
 * 
 * @param users_id
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @return
 */
public SearchResult<User> getUsersList(long user_level, int start, int max, String orderby, boolean asc) {
    try {
        if (authLevelUtil.checkAdminLevel(user_level)) {
            SearchResult<User> sresult = new SearchResult<User>();
            sresult.setObjectName(User.class.getName());
            sresult.setRecords(usersDao.count());

            // get all users
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<User> cq = cb.createQuery(User.class);
            Root<User> c = cq.from(User.class);
            Predicate condition = cb.equal(c.get("deleted"), false);
            cq.where(condition);
            cq.distinct(asc);
            if (asc) {
                cq.orderBy(cb.asc(c.get(orderby)));
            } else {
                cq.orderBy(cb.desc(c.get(orderby)));
            }
            TypedQuery<User> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<User> ll = q.getResultList();
            sresult.setResult(ll);
            return sresult;
        }
    } catch (Exception ex2) {
        log.error("[getUsersList] " + ex2);
    }
    return null;
}

From source file:org.apache.openmeetings.data.user.UserManager.java

/**
 * suche eines Bentzers/*from w w  w  .  ja  v  a 2  s.c  om*/
 * 
 * @param user_level
 * @param searchstring
 * @param max
 * @param start
 * @return
 */
public List<User> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start,
        String orderby, boolean asc) {
    if (authLevelUtil.checkAdminLevel(user_level)) {
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<User> cq = cb.createQuery(User.class);
            Root<User> c = cq.from(User.class);
            Expression<String> literal = cb.literal("%" + searchstring + "%");
            Path<String> path = c.get(searchcriteria);
            Predicate predicate = cb.like(path, literal);
            Predicate condition = cb.notEqual(c.get("deleted"), true);
            cq.where(condition, predicate);
            cq.distinct(asc);
            if (asc) {
                cq.orderBy(cb.asc(c.get(orderby)));
            } else {
                cq.orderBy(cb.desc(c.get(orderby)));
            }
            TypedQuery<User> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<User> contactsZ = q.getResultList();
            return contactsZ;
        } catch (Exception ex2) {
            log.error("searchUser", ex2);
        }
    }
    return null;
}