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.querybyexample.jpa.GenericRepository.java

/**
 * Find and load a list of E instance.//from  ww  w.  ja v  a  2  s  .  c o m
 *
 * @param entity a sample entity whose non-null properties may be used as
 * search hints
 * @param searchParameters carries additional search information
 * @return the entities matching the search.
 */
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List<E> find(E entity, SearchParameters sp) {
    if (sp.hasNamedQuery()) {
        return byNamedQueryUtil.findByNamedQuery(sp);
    }
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<E> criteriaQuery = builder.createQuery(type);
    if (sp.getDistinct()) {
        criteriaQuery.distinct(true);
    }
    Root<E> root = criteriaQuery.from(type);

    // predicate
    Predicate predicate = getPredicate(root, builder, entity, sp);
    if (predicate != null) {
        criteriaQuery = criteriaQuery.where(predicate);
    }

    // left join
    for (SingularAttribute<?, ?> arg : sp.getLeftJoins()) {
        root.fetch((SingularAttribute<E, ?>) arg, JoinType.LEFT);
    }

    // order by
    criteriaQuery.orderBy(orderByUtil.buildJpaOrders(sp.getOrders(), root, builder, sp));

    TypedQuery<E> typedQuery = entityManager.createQuery(criteriaQuery);
    applyCacheHints(typedQuery, sp);
    applyPagination(typedQuery, sp);
    List<E> entities = typedQuery.getResultList();
    log.debug("Returned {} elements", entities.size());

    return entities;
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.SessionDaoImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    this.findAllSessions = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<SessionImpl>>() {
                @Override//from  w w  w .jav  a 2 s .  co m
                public CriteriaQuery<SessionImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<SessionImpl> criteriaQuery = cb.createQuery(SessionImpl.class);
                    final Root<SessionImpl> definitionRoot = criteriaQuery.from(SessionImpl.class);
                    criteriaQuery.select(definitionRoot);

                    return criteriaQuery;
                }
            });
}

From source file:org.querybyexample.jpa.GenericRepository.java

/**
 * Count the number of E instances./*from  ww w  .j av a  2  s  . c om*/
 *
 * @param entity a sample entity whose non-null properties may be used as
 * search hint
 * @param searchParameters carries additional search information
 * @return the number of entities matching the search.
 */
@Transactional(readOnly = true)
public int findCount(E entity, SearchParameters sp) {
    checkNotNull(entity, "The entity cannot be null");
    checkNotNull(sp, "The searchParameters cannot be null");

    if (sp.hasNamedQuery()) {
        return byNamedQueryUtil.numberByNamedQuery(sp).intValue();
    }
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
    Root<E> root = criteriaQuery.from(type);

    if (sp.getDistinct()) {
        criteriaQuery = criteriaQuery.select(builder.countDistinct(root));
    } else {
        criteriaQuery = criteriaQuery.select(builder.count(root));
    }

    // predicate
    Predicate predicate = getPredicate(root, builder, entity, sp);
    if (predicate != null) {
        criteriaQuery = criteriaQuery.where(predicate);
    }

    orderByUtil.forceJoinOrder(root, sp);

    TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery);

    applyCacheHints(typedQuery, sp);
    Long count = typedQuery.getSingleResult();

    if (count != null) {
        return count.intValue();
    } else {
        log.warn("findCount returned null");
        return 0;
    }
}

From source file:dk.dma.msinm.service.AreaService.java

/**
 * Looks up an area by name//from  w  w  w.  j  av a 2s  .co m
 * @param name the name to search for
 * @param lang the language. Optional
 * @param parentId the parent ID. Optional
 * @return The matching area, or null if not found
 */
public Area findByName(String name, String lang, Integer parentId) {
    // Sanity check
    if (StringUtils.isBlank(name)) {
        return null;
    }

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Area> areaQuery = builder.createQuery(Area.class);

    Root<Area> areaRoot = areaQuery.from(Area.class);

    // Build the predicate
    PredicateHelper<Area> predicateBuilder = new PredicateHelper<>(builder, areaQuery);

    // Match the name
    Join<Area, AreaDesc> descs = areaRoot.join("descs", JoinType.LEFT);
    predicateBuilder.like(descs.get("name"), name);
    // Optionally, match the language
    if (StringUtils.isNotBlank(lang)) {
        predicateBuilder.equals(descs.get("lang"), lang);
    }

    // Optionally, match the parent
    if (parentId != null) {
        areaRoot.join("parent", JoinType.LEFT);
        Path<Area> parent = areaRoot.get("parent");
        predicateBuilder.equals(parent.get("id"), parentId);
    }

    // Complete the query
    areaQuery.select(areaRoot).distinct(true).where(predicateBuilder.where());

    // Execute the query and update the search result
    List<Area> result = em.createQuery(areaQuery).getResultList();

    return result.size() > 0 ? result.get(0) : null;
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

public List<ConsumedResourceRelationEntity> getConsumedSlaveRelations(ResourceEntity slaveResource) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ConsumedResourceRelationEntity> q = cb.createQuery(ConsumedResourceRelationEntity.class);
    Root<ConsumedResourceRelationEntity> r = q.from(ConsumedResourceRelationEntity.class);
    Join<ConsumedResourceRelationEntity, ResourceEntity> slaveResourceJoin = r.join("slaveResource");
    q.where(cb.equal(slaveResourceJoin.get("id"), slaveResource.getId()));

    TypedQuery<ConsumedResourceRelationEntity> query = entityManager.createQuery(q);
    return query.getResultList();
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

public List<ProvidedResourceRelationEntity> getProvidedSlaveRelations(ResourceEntity slaveResource) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProvidedResourceRelationEntity> q = cb.createQuery(ProvidedResourceRelationEntity.class);
    Root<ProvidedResourceRelationEntity> r = q.from(ProvidedResourceRelationEntity.class);
    Join<ProvidedResourceRelationEntity, ResourceEntity> slaveResourceJoin = r.join("slaveResource");
    q.where(cb.equal(slaveResourceJoin.get("id"), slaveResource.getId()));

    TypedQuery<ProvidedResourceRelationEntity> query = entityManager.createQuery(q);
    return query.getResultList();
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

protected List<AbstractResourceRelationEntity> getConsumedRelationsByMasterAndSlave(
        ResourceEntity masterResource, Set<ResourceEntity> slaveResources, String identifier) {
    List<AbstractResourceRelationEntity> consumed = new ArrayList<>();
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ConsumedResourceRelationEntity> q = cb.createQuery(ConsumedResourceRelationEntity.class);
    Root<ConsumedResourceRelationEntity> r = q.from(ConsumedResourceRelationEntity.class);
    Predicate masterResourceIs = cb.equal(r.<ResourceEntity>get("masterResource"), masterResource);
    Predicate slaveResourceIn = r.<ResourceEntity>get("slaveResource").in(slaveResources);

    if (!StringUtils.isEmpty(identifier)) {
        Predicate identifierIs = cb.equal(r.<String>get("identifier"), identifier);
        q.where(cb.and(masterResourceIs, slaveResourceIn, identifierIs));
    } else {/*from  w  ww.ja  v  a2 s . c  om*/
        q.where(cb.and(masterResourceIs, slaveResourceIn));
    }

    TypedQuery<ConsumedResourceRelationEntity> query = entityManager.createQuery(q);
    List<ConsumedResourceRelationEntity> result = query.getResultList();
    for (ConsumedResourceRelationEntity rel : result) {
        consumed.add(rel);
    }
    return consumed;
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

protected List<AbstractResourceRelationEntity> getProvidedRelationsByMasterAndSlave(
        ResourceEntity masterResource, Set<ResourceEntity> slaveResources, String identifier) {
    List<AbstractResourceRelationEntity> provided = new ArrayList<>();
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProvidedResourceRelationEntity> q = cb.createQuery(ProvidedResourceRelationEntity.class);
    Root<ProvidedResourceRelationEntity> r = q.from(ProvidedResourceRelationEntity.class);
    Predicate masterResourceIs = cb.equal(r.<ResourceEntity>get("masterResource"), masterResource);
    Predicate slaveResourceIn = r.<ResourceEntity>get("slaveResource").in(slaveResources);

    if (!StringUtils.isEmpty(identifier)) {
        Predicate identifierIs = cb.equal(r.<String>get("identifier"), identifier);
        q.where(cb.and(masterResourceIs, slaveResourceIn, identifierIs));
    } else {/*from w w  w.  java2 s .  com*/
        q.where(cb.and(masterResourceIs, slaveResourceIn));
    }

    TypedQuery<ProvidedResourceRelationEntity> query = entityManager.createQuery(q);
    List<ProvidedResourceRelationEntity> result = query.getResultList();
    for (ProvidedResourceRelationEntity rel : result) {
        provided.add(rel);
    }
    return provided;
}

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

protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    Assert.notNull(criteriaQuery);/*  w  w w  .  j av a  2  s  .c  om*/
    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));

    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:de.hopmann.msc.slave.service.PackageInstallationBean.java

public PackageInstallationEntity getInstallationEntity(PackageResolved packageModel,
        Set<PackageInstallationEntity> requiredDependencies, PackageInstallerHolder packageInstallerHolder) {
    try {/*from   w  ww. j a  va  2s  .c o m*/

        // 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;
    }
}