Example usage for javax.persistence.criteria CriteriaQuery select

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

Introduction

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

Prototype

CriteriaQuery<T> select(Selection<? extends T> selection);

Source Link

Document

Specify the item that is to be returned in the query result.

Usage

From source file:net.groupbuy.dao.impl.ProductDaoImpl.java

public List<Product> findList(ProductCategory productCategory, Date beginDate, Date endDate, Integer first,
        Integer count) {/*from  www.j av  a2  s .  c om*/
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isMarketable"), true));
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
    }
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate));
    }
    criteriaQuery.where(restrictions);
    criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")));
    return super.findList(criteriaQuery, first, count, null, null);
}

From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    this.nameParameter = this.createParameterExpression(String.class, "name");

    this.findAllAccountsQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<LocalAccountPersonImpl>>() {
                @Override//from   w w  w  .  j av  a  2  s  . co  m
                public CriteriaQuery<LocalAccountPersonImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb
                            .createQuery(LocalAccountPersonImpl.class);
                    final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery
                            .from(LocalAccountPersonImpl.class);
                    accountRoot.fetch(LocalAccountPersonImpl_.attributes, JoinType.LEFT)
                            .fetch(LocalAccountPersonAttributeImpl_.values, JoinType.LEFT);
                    criteriaQuery.select(accountRoot);

                    return criteriaQuery;
                }
            });

    this.findAccountByNameQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<LocalAccountPersonImpl>>() {
                @Override
                public CriteriaQuery<LocalAccountPersonImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb
                            .createQuery(LocalAccountPersonImpl.class);
                    final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery
                            .from(LocalAccountPersonImpl.class);
                    accountRoot.fetch(LocalAccountPersonImpl_.attributes, JoinType.LEFT)
                            .fetch(LocalAccountPersonAttributeImpl_.values, JoinType.LEFT);
                    criteriaQuery.select(accountRoot);
                    criteriaQuery.where(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), nameParameter));

                    return criteriaQuery;
                }
            });

    this.findAvailableAttributesQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<String>>() {
                @Override
                public CriteriaQuery<String> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<String> criteriaQuery = cb.createQuery(String.class);
                    final Root<LocalAccountPersonAttributeImpl> accountRoot = criteriaQuery
                            .from(LocalAccountPersonAttributeImpl.class);
                    criteriaQuery.select(accountRoot.get(LocalAccountPersonAttributeImpl_.name));
                    criteriaQuery.distinct(true);

                    return criteriaQuery;
                }
            });
}

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * subquery: in// w w w. j ava  2 s .  c om
 * SELECT e FROM jpa_query_employee e WHERE e IN (SELECT emp FROM jpa_query_project p JOIN p.employees pe WHERE p.name = :projectname)
 */
@Transactional
public void doWhere1() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
    Root<Employee> e = c.from(Employee.class);

    // subquery
    Subquery<Employee> sq = c.subquery(Employee.class);
    Root<Project> p = sq.from(Project.class);
    Join<Project, Employee> pe = p.join("employees");
    sq.select(pe).where(cb.equal(p.get("name"), cb.parameter(String.class, "projectname")));

    //
    c.select(e).where(cb.in(e).value(sq));
}

From source file:net.groupbuy.dao.impl.ProductDaoImpl.java

public Long count(Member favoriteMember, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isGift,
        Boolean isOutOfStock, Boolean isStockAlert) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (favoriteMember != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.join("favoriteMembers"), favoriteMember));
    }/*from   w ww. j  a v a2s .  c o m*/
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

From source file:org.ow2.proactive.scheduling.api.graphql.fetchers.DatabaseConnectionFetcher.java

/**
 * Adaptation of the algorithm defined in the GraphQL specification.
 * <p>//from   w w  w.java 2 s .c  o  m
 * Please look at the following link for more details:
 * https://facebook.github.io/relay/graphql/connections.htm#sec-Pagination-algorithm
 * <p>
 * The opaque cursor that is returned to the client makes use of the entity ID internally.
 */
protected ExtendedConnection createPaginatedConnection(DataFetchingEnvironment environment,
        Class<E> entityClass, Function<Root<E>, Path<? extends Number>> entityId,
        Comparator<E> entityComparator, BiFunction<CriteriaBuilder, Root<E>, List<Predicate[]>> criteria,
        CursorMapper<T, Integer> cursorMapper) {

    Integer first = environment.getArgument(FIRST.getName());
    Integer last = environment.getArgument(LAST.getName());

    Integer after = cursorMapper.getOffsetFromCursor(environment.getArgument(AFTER.getName()));
    Integer before = cursorMapper.getOffsetFromCursor(environment.getArgument(BEFORE.getName()));

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<E> entityRoot = criteriaQuery.from(entityClass);
    Path<? extends Number> entityIdPath = entityId.apply(entityRoot);

    Predicate cursorPredicate = createCursorPredicate(criteriaBuilder, entityIdPath, after, before);

    int maxResults = applySlicing(criteriaQuery, criteriaBuilder, entityIdPath, first, last);

    CriteriaQuery<E> select = criteriaQuery.select(entityRoot);

    List<Predicate[]> predicates = criteria.apply(criteriaBuilder, entityRoot);

    Predicate[] wherePredicate = buildWherePredicate(predicates, cursorPredicate, criteriaBuilder);

    if (wherePredicate.length > 0) {
        select.where(wherePredicate);
    }

    TypedQuery<E> query = entityManager.createQuery(select);

    if (maxResults > -1) {
        query.setMaxResults(maxResults);
    }

    Stream<E> dataStream = query.getResultList().stream();

    // if last is provided, reverse the stream
    // in order to get results sorted in ascending order based on entities ID
    if (last != null) {
        dataStream = dataStream.sorted(entityComparator);
    }

    Stream<T> data = dataMapping(dataStream);

    ExtendedConnection connection = createRelayConnection(entityManager, entityClass, criteriaBuilder,
            wherePredicate, cursorMapper, data, first, last);

    return connection;
}

From source file:org.osiam.resource_server.storage.dao.ResourceDao.java

public <T extends ResourceEntity> SearchResult<T> search(Class<T> clazz, ParseTree filterTree, int count,
        int startIndex, String sortBy, String sortOrder, FilterParser<T> filterParser) {

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<T> resourceQuery = cb.createQuery(clazz);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    Subquery<Long> internalIdQuery = resourceQuery.subquery(Long.class);
    Root<T> internalIdRoot = internalIdQuery.from(clazz);
    internalIdQuery.select(internalIdRoot.get(ResourceEntity_.internalId));

    if (filterTree != null && filterTree.getChildCount() > 0) {
        Predicate predicate = filterParser.createPredicateAndJoin(filterTree, internalIdRoot);
        internalIdQuery.where(predicate);
    }//from   w  w  w  . ja v  a2 s  .c om

    resourceQuery.select(resourceRoot)
            .where(cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    // TODO: evaluate if a User-/GroupDao supplied default sortBy field is possible
    Expression<?> sortByField = resourceRoot.get(ResourceEntity_.id);

    if (sortBy != null && !sortBy.isEmpty()) {
        sortByField = filterParser.createSortByField(sortBy, resourceRoot);
    }

    // default order is ascending
    Order order = cb.asc(sortByField);

    if (sortOrder.equalsIgnoreCase("descending")) {
        order = cb.desc(sortByField);
    }

    resourceQuery.orderBy(order);

    TypedQuery<T> query = em.createQuery(resourceQuery);
    query.setFirstResult(startIndex);
    query.setMaxResults(count);

    List<T> results = query.getResultList();

    long totalResult = getTotalResults(clazz, internalIdQuery);

    return new SearchResult<>(results, totalResult);
}

From source file:com.zero.dao.impl.BaseDaoImpl.java

protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    Assert.notNull(criteriaQuery);/*from   w ww  .jav a 2  s. c  o  m*/
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    addRestrictions(criteriaQuery, filters);

    CriteriaQuery<Long> countCriteriaQuery = criteriaBuilder.createQuery(Long.class);

    for (Root<?> root : criteriaQuery.getRoots()) {
        Root<?> dest = countCriteriaQuery.from(root.getJavaType());
        dest.alias(getAlias(root));
        copyJoins(root, dest);
    }

    Root<?> countRoot = getRoot(countCriteriaQuery, criteriaQuery.getResultType());
    countCriteriaQuery.select(criteriaBuilder.count(countRoot.get("id").<String>get("stcd")));

    if (criteriaQuery.getGroupList() != null) {
        countCriteriaQuery.groupBy(criteriaQuery.getGroupList());
    }
    if (criteriaQuery.getGroupRestriction() != null) {
        countCriteriaQuery.having(criteriaQuery.getGroupRestriction());
    }
    if (criteriaQuery.getRestriction() != null) {
        countCriteriaQuery.where(criteriaQuery.getRestriction());
    }
    return entityManager.createQuery(countCriteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
}

From source file:org.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java

/**
 * Builds the Typed Query//from ww  w.j  a  va 2s .co m
 * @return
 */
public TypedQuery<Connection> buildSingleRelationship() {
    EntityManager em = EntityManagerHolder.get();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Connection> criteria = cb.createQuery(Connection.class);
    Root<Connection> connection = criteria.from(Connection.class);

    Predicate predicate = null;
    if (this.sender != null && this.receiver != null) {
        predicate = cb.equal(connection.get(Connection_.senderId), sender.getId());
        predicate = cb.and(predicate, cb.equal(connection.get(Connection_.receiverId), receiver.getId()));
    }

    CriteriaQuery<Connection> select = criteria.select(connection).distinct(true);
    select.where(predicate);
    TypedQuery<Connection> typedQuery = em.createQuery(select);

    return typedQuery;
}

From source file:com.sfs.captor.controller.UseCaseFlowAction.java

/**
 * check for duplicate alternative flow/*from ww w  . j  a  va  2 s.  c  om*/
 */
private boolean checkForDuplicateAlternateFlow(final UseCase useCase, final String name) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Flow> c = cb.createQuery(Flow.class);
    Root<Flow> obj = c.from(Flow.class);
    c.select(obj).where(cb.equal(obj.<String>get("name"), name), cb.equal(obj.get("useCase"), useCase));
    List<Flow> list = em.createQuery(c).getResultList();
    return (list.size() > 0);
}

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * subquery(equivalent to dowhere1) : exists
 * SELECT e FROM jpa_query_employee e WHERE EXISTS (SELECT p FROM e.projects p WHERE p.name = :projectname)
 *///from   w w w. ja  v  a  2  s.c om
@Transactional
public void doWhere2() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
    Root<Employee> e = c.from(Employee.class);

    // subquery
    Subquery<Project> sq = c.subquery(Project.class);
    // Root<Project> p = sq.from(Project.class);
    Root<Employee> se = sq.correlate(e);
    Join<Employee, Project> p = se.join("projects");
    sq.select(p).where(cb.equal(p.get("name"), cb.parameter(String.class, "projectname")));

    //
    c.select(e).where(cb.exists(sq));
}