Example usage for javax.persistence.criteria CriteriaBuilder createQuery

List of usage examples for javax.persistence.criteria CriteriaBuilder createQuery

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder createQuery.

Prototype

<T> CriteriaQuery<T> createQuery(Class<T> resultClass);

Source Link

Document

Create a CriteriaQuery object with the specified result type.

Usage

From source file:org.openlmis.fulfillment.repository.custom.impl.OrderRepositoryImpl.java

/**
 * Retrieves the distinct UUIDs of the available requesting facilities.
 *//*from  www  .j av  a2  s. c  o m*/
@Override
public List<UUID> getRequestingFacilities(List<UUID> supplyingFacilityIds) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<UUID> query = builder.createQuery(UUID.class);
    Root<Order> root = query.from(Order.class);

    if (!isEmpty(supplyingFacilityIds)) {
        Predicate predicate = builder.disjunction();
        for (Object elem : supplyingFacilityIds) {
            predicate = builder.or(predicate, builder.equal(root.get(SUPPLYING_FACILITY_ID), elem));
        }
        query.where(predicate);
    }

    query.select(root.get(REQUESTING_FACILITY_ID)).distinct(true);

    return entityManager.createQuery(query).getResultList();
}

From source file:de.hopmann.repositories.cran.service.CRANPackageListingService.java

public int getPackageListingCount() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Number> query = cb.createQuery(Number.class);
    query.select(cb.count(query.from(CRANPackageEntity.class)));
    return entityManager.createQuery(query).getSingleResult().intValue();
}

From source file:org.openlmis.fulfillment.repository.custom.impl.OrderRepositoryImpl.java

private Page<Order> search(OrderSearchParams params, Set<UUID> processingPeriodIds, Pageable pageable,
        Set<UUID> availableSupplyingFacilities, Set<UUID> availableRequestingFacilities) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<Order> query = builder.createQuery(Order.class);
    query = prepareQuery(query, params, processingPeriodIds, pageable, false, availableSupplyingFacilities,
            availableRequestingFacilities);
    CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
    countQuery = prepareQuery(countQuery, params, processingPeriodIds, pageable, true,
            availableSupplyingFacilities, availableRequestingFacilities);

    Pageable page = null != pageable ? pageable : new PageRequest(0, Integer.MAX_VALUE);

    Long count = entityManager.createQuery(countQuery).getSingleResult();
    List<Order> result = entityManager.createQuery(query).setMaxResults(page.getPageSize())
            .setFirstResult(page.getPageSize() * page.getPageNumber()).getResultList();

    return new PageImpl<>(result, page, count);
}

From source file:se.kth.csc.persist.JPAStore.java

@Override
public Iterable<Account> findAccounts(boolean onlyAdmin, String query) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Account> q = cb.createQuery(Account.class);
    Root<Account> account = q.from(Account.class);

    Expression<Boolean> expression = null;

    if (onlyAdmin) {
        // This looks like it could be replaced with account.get(Account_.admin), but it can't because of syntax
        expression = cb.equal(account.get(Account_.admin), true);
    }//  w  w  w .  j  av a2  s  . c  o  m

    if (query != null) {
        Expression<Boolean> queryExpression = cb.like(cb.lower(account.get(Account_.name)),
                "%" + query.toLowerCase() + "%");

        if (expression == null) {
            expression = queryExpression;
        } else {
            expression = cb.and(expression, queryExpression);
        }
    }

    if (expression != null) {
        q.where(expression);
    }

    return entityManager.createQuery(q.select(account)).getResultList();
}

From source file:com.aimdek.ccm.dao.impl.StatementRepositoryImpl.java

/**
 * {@inheritDoc}/*  w ww.jav  a  2 s . c o m*/
 */
public Statement findLastStatement() {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statement> query = builder.createQuery(Statement.class);
    Root<Statement> root = query.from(Statement.class);
    query.select(root);
    query.orderBy(builder.desc(root.get(FIELD_CONSTANT_STATEMENT_DATE)));
    try {
        return entityManager.createQuery(query).setMaxResults(1).getSingleResult();
    } catch (NoResultException e) {
        LOGGER.error("Error while retrieving last statement", e);
    }
    return null;
}

From source file:com.qpark.eip.core.spring.auth.dao.AuthorityDao.java

/**
 * Get the {@link AuthenticationType}s out of the database.
 *
 * @param enabled/*from   w ww .j  a va  2s  .  c om*/
 *            if not <code>null</code> and <code>true</code> only the
 *            enabled {@link AuthenticationType}s are replied.
 * @return the list of {@link AuthenticationType}s.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<AuthenticationType> getAuthenticationTypes(final Boolean enabled) {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<AuthenticationType> q = cb.createQuery(AuthenticationType.class);
    Root<AuthenticationType> c = q.from(AuthenticationType.class);
    Predicate ands = cb.conjunction();
    ands.getExpressions().add(cb.equal(c.<String>get(AuthenticationType_.context), this.getContextName()));
    if (enabled != null) {
        ands.getExpressions().add(cb.equal(c.<Boolean>get(AuthenticationType_.enabled), enabled));
    }
    q.where(ands);
    q.orderBy(cb.asc(c.<String>get(AuthenticationType_.userName)));
    TypedQuery<AuthenticationType> typedQuery = this.em.createQuery(q);
    List<AuthenticationType> list = typedQuery.getResultList();
    for (AuthenticationType auth : list) {
        for (GrantedAuthorityType gr : auth.getGrantedAuthority()) {
            gr.getRoleName();
        }
        for (int i = 0; i < auth.getGrantedAuthority().size(); i++) {
            // eager loading...
            auth.getGrantedAuthority().get(i);
        }
    }
    return list;
}

From source file:com.qpark.eip.core.spring.auth.dao.AuthorityDao.java

/**
 * Get the granted number of calls.//w  ww . j  a  va 2s .co  m
 *
 * @param userName
 *            the user name.
 * @param serviceName
 *            the service name.
 * @param operationName
 *            the operation name.
 * @return the number of calls.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public int getGrantedRequestNumber(final String userName, final String serviceName,
        final String operationName) {
    Integer requests = 0;
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<AuthenticationType> q = cb.createQuery(AuthenticationType.class);
    Root<AuthenticationType> c = q.from(AuthenticationType.class);
    q.where(cb.equal(c.<String>get(AuthenticationType_.context), this.contextNameProvider.getContextName()),
            cb.equal(c.<String>get(AuthenticationType_.userName), userName));

    TypedQuery<AuthenticationType> typedQuery = this.em.createQuery(q);
    try {
        AuthenticationType log = typedQuery.getSingleResult();
        for (GrantedAuthorityType role : log.getGrantedAuthority()) {
            if (this.getRoleName(serviceName, operationName).equals(role.getRoleName())) {
                requests = role.getMaxRequests();
            }
        }
        if (requests == null) {
            requests = Integer.MAX_VALUE;
        }
    } catch (Exception e) {
        requests = 0;
    }
    return requests;
}

From source file:org.sloth.persistence.impl.ObservationDaoImpl.java

@Override
public Collection<Observation> getByUser(User u) throws NullPointerException, IllegalArgumentException {
    if (u == null) {
        throw new NullPointerException();
    }// ww  w. j a  va 2  s . c om
    if (u.isNew()) {
        throw new EntityNotKnownException();
    }
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Observation> cq = cb.createQuery(Observation.class);
    Root<Observation> o = cq.from(Observation.class);
    cq.select(o).where(cb.equal(o.get(Observation_.user), u));
    Collection<Observation> result = getEntityManager().createQuery(cq).getResultList();
    logger.info("{} Observations by User {}.", result.size(), u);
    return result;
}

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);/*from w  w w .  ja  v  a 2 s . c  o m*/
    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 {
        return this.entityManager.createQuery(c).getSingleResult();
    } catch (final Exception e) {
        log.debug(e.getMessage(), e);
        return null;
    }
}

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

public <T extends ResourceEntity, V> boolean isUniqueAttributeAlreadyTaken(String attributeValue, String id,
        SingularAttribute<? super T, V> attribute, Class<T> clazz) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<T> resource = cq.from(clazz);

    cq.select(cb.countDistinct(resource));

    Predicate predicate = cb.equal(resource.get(attribute), attributeValue);
    if (id != null) {
        Predicate ignoreId = cb.notEqual(resource.get(ResourceEntity_.id), id);
        predicate = cb.and(predicate, ignoreId);
    }/* w  ww. j a  va  2s  .co  m*/
    cq.where(predicate);

    TypedQuery<Long> countQuery = em.createQuery(cq);

    return countQuery.getSingleResult() > 0;
}