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:com.netflix.genie.core.jpa.specifications.JpaClusterSpecs.java

/**
 * Get all the clusters given the specified parameters.
 *
 * @param clusterCriteria The cluster criteria
 * @param commandCriteria The command Criteria
 * @return The specification//from  w ww.  j  a v  a  2  s. co  m
 */
public static Specification<ClusterEntity> findByClusterAndCommandCriteria(
        final ClusterCriteria clusterCriteria, final Set<String> commandCriteria) {
    return (final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        final Join<ClusterEntity, CommandEntity> commands = root.join(ClusterEntity_.commands);

        cq.distinct(true);

        predicates.add(cb.equal(root.get(ClusterEntity_.status), ClusterStatus.UP));

        if (clusterCriteria != null && clusterCriteria.getTags() != null
                && !clusterCriteria.getTags().isEmpty()) {
            predicates.add(cb.like(root.get(ClusterEntity_.tags),
                    JpaSpecificationUtils.getTagLikeString(clusterCriteria.getTags())));
        }

        predicates.add(cb.equal(commands.get(CommandEntity_.status), CommandStatus.ACTIVE));

        if (commandCriteria != null && !commandCriteria.isEmpty()) {
            predicates.add(cb.like(commands.get(CommandEntity_.tags),
                    JpaSpecificationUtils.getTagLikeString(commandCriteria)));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

From source file:com.netflix.genie.server.repository.jpa.ClusterSpecs.java

/**
 * Get all the clusters given the specified parameters.
 *
 * @param clusterCriteria The cluster criteria
 * @param commandCriteria The command Criteria
 * @return The specification//from  ww  w .j  av a  2  s  . co m
 */
public static Specification<Cluster> findByClusterAndCommandCriteria(final ClusterCriteria clusterCriteria,
        final Set<String> commandCriteria) {
    return new Specification<Cluster>() {
        @Override
        public Predicate toPredicate(final Root<Cluster> root, final CriteriaQuery<?> cq,
                final CriteriaBuilder cb) {
            final List<Predicate> predicates = new ArrayList<>();
            final Join<Cluster, Command> commands = root.join(Cluster_.commands);

            cq.distinct(true);

            predicates.add(cb.equal(commands.get(Command_.status), CommandStatus.ACTIVE));
            predicates.add(cb.equal(root.get(Cluster_.status), ClusterStatus.UP));

            if (commandCriteria != null) {
                for (final String tag : commandCriteria) {
                    predicates.add(cb.isMember(tag, commands.get(Command_.tags)));

                }
            }

            if (clusterCriteria != null) {
                for (final String tag : clusterCriteria.getTags()) {
                    predicates.add(cb.isMember(tag, root.get(Cluster_.tags)));
                }
            }

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
}

From source file:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Creates a query that fetches objects based on their IDs
 * //from w  w  w. j a  v  a2 s  .com
 * @param entityManager
 *            the entity manager
 * @param entityClass
 *            the entity class
 * @param ids
 *            the IDs of the desired entities
 * @param sortOrders
 *            the sorting information
 * @param fetchJoins
 *            the desired fetch joins
 * @return
 */
public static <ID, T> CriteriaQuery<T> createFetchQuery(EntityManager entityManager, Class<T> entityClass,
        List<ID> ids, SortOrders sortOrders, FetchJoinInformation[] fetchJoins) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    boolean distinct = addFetchJoinInformation(root, fetchJoins);

    Expression<String> exp = root.get(DynamoConstants.ID);
    cq.where(exp.in(ids));
    cq.distinct(distinct);

    return addSortInformation(builder, cq, root, sortOrders == null ? null : sortOrders.toArray());
}

From source file:org.jdal.dao.jpa.JpaUtils.java

/**
 * Copy criteria without selection and order.
 * @param from source Criteria.//  www  . j a  v a 2 s.  co m
 * @param to destination Criteria.
 */
private static void copyCriteriaWithoutSelectionAndOrder(CriteriaQuery<?> from, CriteriaQuery<?> to) {
    if (isEclipseLink(from) && from.getRestriction() != null) {
        // EclipseLink adds roots from predicate paths to critera. Skip copying 
        // roots as workaround.
    } else {
        // 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());

    if (from.getGroupRestriction() != null)
        to.having(from.getGroupRestriction());

    Predicate predicate = from.getRestriction();
    if (predicate != null)
        to.where(predicate);
}

From source file:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Creates a query to fetch an object based on a value of a unique property
 * /*ww w.j av  a2  s.c  o  m*/
 * @param entityManager
 *            the entity manager
 * @param entityClass
 *            the entity class
 * @param fetchJoins
 *            the fetch joins to include
 * @param propertyName
 *            name of the property to search on
 * @param value
 *            value of the property to search on
 * @return
 */
public static <T> CriteriaQuery<T> createUniquePropertyFetchQuery(EntityManager entityManager,
        Class<T> entityClass, FetchJoinInformation[] fetchJoins, String propertyName, Object value,
        boolean caseSensitive) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    addFetchJoinInformation(root, fetchJoins);

    Predicate equals = null;
    if (value instanceof String && !caseSensitive) {
        equals = builder.equal(builder.upper(root.get(propertyName).as(String.class)),
                ((String) value).toUpperCase());
    } else {
        equals = builder.equal(root.get(propertyName), value);
    }
    cq.where(equals);
    cq.distinct(true);

    return cq;
}

From source file:net.dontdrinkandroot.persistence.dao.ExampleGeneratedIdEntityDaoImpl.java

@Override
@Transactional(readOnly = true)/* ww w . j  av a  2s .c  o  m*/
public List<ExampleGeneratedIdEntity> findByOtherText(final String text) {
    final CriteriaBuilder builder = this.getCriteriaBuilder();
    final CriteriaQuery<ExampleGeneratedIdEntity> criteriaQuery = builder.createQuery(this.entityClass);
    criteriaQuery.distinct(true);
    final Root<ExampleGeneratedIdEntity> root = criteriaQuery.from(this.entityClass);

    final ListJoin<ExampleGeneratedIdEntity, ExampleIdEntity> join = root
            .join(ExampleGeneratedIdEntity_.otherEntities);

    criteriaQuery.where(builder.equal(join.get(ExampleIdEntity_.text), text));

    return this.find(criteriaQuery);
}

From source file:org.openregistry.core.repository.jpa.JpaReferenceRepository.java

public Region getRegionByCodeOrName(final String code) {
    final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();

    final CriteriaQuery<JpaRegionImpl> c = criteriaBuilder.createQuery(JpaRegionImpl.class);
    c.distinct(true);
    final Root<JpaRegionImpl> region = c.from(JpaRegionImpl.class);
    c.where(criteriaBuilder.or(criteriaBuilder.equal(region.get(JpaRegionImpl_.code), code),
            criteriaBuilder.like(region.get(JpaRegionImpl_.name), code)));

    try {//ww w.j  a v a  2  s.co m
        return this.entityManager.createQuery(c).getSingleResult();
    } catch (final Exception e) {
        log.debug(e.getMessage(), e);
        return null;
    }
}

From source file:com.order.erp.web.controller.SystemController.java

@RequestMapping(path = "amoeba", method = RequestMethod.GET)
public String amoebaIndex(HttpServletRequest request,
        @RequestParam(name = "keyword", required = false) String keyword,
        @PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.ASC) Pageable pageable,
        ModelMap model) {//from   ww  w.  jav  a 2 s. c o  m
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User me = staffService.findByAccountUsername(((UserDetails) principal).getUsername());
    Company company = me.getCompany();

    final String finalKeyword = keyword;
    final Company finalCompany = company;
    Page<Amoeba> page = adminService.findAmoebas(new Specification<Amoeba>() {
        public Predicate toPredicate(Root<Amoeba> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            query.distinct(true);
            Predicate p1 = cb.equal(root.get("company").as(Company.class), finalCompany);
            Predicate p2 = cb.conjunction();
            if (StringUtils.isNotBlank(finalKeyword)) {
                p2 = cb.like(root.get("name").as(String.class), "%" + finalKeyword + "%");
            }
            Predicate p_result = cb.and(p1, p2);
            return p_result;
        }
    }, pageable);

    model.put("user", me);
    model.put("company", company);
    model.put("page", page);
    String json = JSON.toJSONString(page, SerializerFeature.PrettyFormat);
    System.out.println(json);
    return "/system/amoeba_list";
}

From source file:com.order.erp.web.controller.SystemController.java

@RequestMapping(path = "staff", method = RequestMethod.GET)
public String staffIndex(HttpServletRequest request,
        @RequestParam(name = "keyword", required = false) String keyword,
        @PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.ASC) Pageable pageable,
        ModelMap model) {/*w  w  w. ja v  a 2s.c  om*/
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User me = staffService.findByAccountUsername(((UserDetails) principal).getUsername());
    Company company = me.getCompany();
    //List<User> userList = userService.findUsersByAmoebaId(company.getId());

    final User meStaff = me;
    final String finalKeyword = keyword;
    final Company finalCompany = company;
    Page<User> page = staffService.findUsers(new Specification<User>() {
        public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            query.distinct(true);
            Predicate p1 = cb.equal(root.get("company").as(Company.class), finalCompany);
            Predicate p2 = cb.conjunction();
            if (StringUtils.isNotBlank(finalKeyword)) {
                Predicate p1_like = cb.like(root.get("account").get("username").as(String.class),
                        "%" + finalKeyword + "%");
                Predicate p2_like = cb.like(root.get("realname").as(String.class), "%" + finalKeyword + "%");
                p2 = cb.or(p1_like, p2_like);
            }
            Predicate p3 = cb.notEqual(root.as(User.class), meStaff);
            Predicate p_result = cb.and(p1, p2, p3);
            return p_result;
        }
    }, pageable);

    model.put("user", me);
    model.put("company", company);
    model.put("page", page);
    return "/system/staff_list";
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private List<Product> getProducts_Mercilessly() {
    return transactionTemplate.execute(new TransactionCallback<List<Product>>() {
        @Override/*from  w w  w.  j av a2 s. c  o m*/
        public List<Product> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Product> product = query.from(Product.class);
            query.select(product);
            query.distinct(true);

            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(product.get(Product_.name)), "%tv%"));

            Subquery<Long> subQuery = query.subquery(Long.class);
            Root<Image> infoRoot = subQuery.from(Image.class);
            Join<Image, Product> productJoin = infoRoot.join(Image_.product);
            subQuery.select(productJoin.<Long>get(Product_.id));

            subQuery.where(cb.gt(infoRoot.get(Image_.index), 0));
            criteria.add(cb.in(product.get(Product_.id)).value(subQuery));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            return entityManager.createQuery(query).getResultList();
        }
    });
}