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:eu.uqasar.service.AbstractService.java

protected Long performDistinctCountWithEqualPredicate(final Attribute<T, ?> attr, Object value) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> query = cb.createQuery(Long.class);
    Root<T> root = query.from(clazz);
    query.where(cb.equal(root.get(attr.getName()), value));
    query.select(cb.countDistinct(root));
    return em.createQuery(query).getSingleResult();
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.CriteriaTranslatorImpl.java

@SuppressWarnings("unchecked")
protected TypedQuery<Serializable> constructQuery(DynamicEntityDao dynamicEntityDao, String ceilingEntity,
        List<FilterMapping> filterMappings, boolean isCount, boolean isMax, Integer firstResult,
        Integer maxResults, String maxField) {

    CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();

    Class<Serializable> ceilingMarker;
    try {/*w  w  w  . jav a2  s. c om*/
        ceilingMarker = (Class<Serializable>) Class.forName(ceilingEntity);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }

    Class<Serializable> securityRoot = rowSecurityService.getFetchRestrictionRoot(
            adminSecurityService.getPersistentAdminUser(), ceilingMarker, filterMappings);
    if (securityRoot != null) {
        ceilingMarker = securityRoot;
    }

    Class<Serializable> ceilingClass = determineRoot(dynamicEntityDao, ceilingMarker, filterMappings);
    CriteriaQuery<Serializable> criteria = criteriaBuilder.createQuery(ceilingMarker);
    Root<Serializable> original = criteria.from(ceilingClass);

    if (isCount) {
        criteria.select(criteriaBuilder.count(original));
    } else if (isMax) {
        criteria.select(criteriaBuilder.max((Path<Number>) ((Object) original.get(maxField))));
    } else {
        criteria.select(original);
    }

    List<Predicate> restrictions = new ArrayList<Predicate>();
    List<Order> sorts = new ArrayList<Order>();
    addRestrictions(ceilingEntity, filterMappings, criteriaBuilder, original, restrictions, sorts, criteria);

    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    if (!isCount && !isMax) {
        criteria.orderBy(sorts.toArray(new Order[sorts.size()]));
        //If someone provides a firstResult value, then there is generally pagination going on.
        //In order to produce consistent results, especially with certain databases such as PostgreSQL, 
        //there has to be an "order by" clause.  We'll add one here if we can.
        if (firstResult != null && sorts.isEmpty()) {
            Map<String, Object> idMetaData = dynamicEntityDao.getIdMetadata(ceilingClass);
            if (idMetaData != null) {
                Object idFldName = idMetaData.get("name");
                Object type = idMetaData.get("type");
                if ((idFldName instanceof String) && (type instanceof SingleColumnType)) {
                    criteria.orderBy(criteriaBuilder.asc(original.get((String) idFldName)));
                }
            }
        }
    }
    TypedQuery<Serializable> response = dynamicEntityDao.getStandardEntityManager().createQuery(criteria);

    if (!isCount && !isMax) {
        addPaging(response, firstResult, maxResults);
    }

    return response;
}

From source file:com.sfs.ucm.controller.SpecificationAction.java

/**
 * Get count of specification rules//  w w  w.jav  a 2  s  .co  m
 * 
 * @return count
 */
private Long getSpecificationRuleCount() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> c = cb.createQuery(Long.class);
    c.select(cb.count(c.from(SpecificationRule.class)));
    return em.createQuery(c).getSingleResult();
}

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

/**
 * load requirements/*from  ww w .  j ava2 s  .  c o m*/
 */
private void loadList() throws UCMException {

    Set<String> versions = this.projectService.findActiveProductReleaseVersions(this.authUser, this.project);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Requirement> c = cb.createQuery(Requirement.class);
    Root<Requirement> obj = c.from(Requirement.class);
    c.select(obj).where(cb.equal(obj.get("project"), this.project),
            obj.get("productRelease").get("version").in(versions)).orderBy(cb.asc(obj.get("id")));
    this.requirements = em.createQuery(c).getResultList();

}

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

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

    this.getUsersByPrimaryEmailQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<ConferenceUserImpl>>() {
                @Override//from   ww w. ja v a2  s . co m
                public CriteriaQuery<ConferenceUserImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<ConferenceUserImpl> criteriaQuery = cb
                            .createQuery(ConferenceUserImpl.class);
                    final Root<ConferenceUserImpl> definitionRoot = criteriaQuery
                            .from(ConferenceUserImpl.class);
                    criteriaQuery.select(definitionRoot);
                    criteriaQuery
                            .where(cb.equal(definitionRoot.get(ConferenceUserImpl_.email), emailParameter));

                    return criteriaQuery;
                }
            });

    this.getUsersByAnyEmailQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<ConferenceUserImpl>>() {
                @Override
                public CriteriaQuery<ConferenceUserImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<ConferenceUserImpl> criteriaQuery = cb
                            .createQuery(ConferenceUserImpl.class);
                    final Root<ConferenceUserImpl> definitionRoot = criteriaQuery
                            .from(ConferenceUserImpl.class);
                    criteriaQuery.select(definitionRoot);
                    criteriaQuery.where(
                            cb.or(cb.equal(definitionRoot.get(ConferenceUserImpl_.email), emailParameter),
                                    cb.isMember(emailParameter,
                                            definitionRoot.get(ConferenceUserImpl_.additionalEmails))));

                    return criteriaQuery;
                }
            });
}

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

public TypedQuery<Long> buildFilterCount() {
    EntityManager em = EntityManagerHolder.get();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = cb.createQuery(Long.class);
    Root<Connection> relationship = criteria.from(Connection.class);
    Join<Connection, Profile> receiver = relationship.join(Connection_.receiver);
    CriteriaQuery<Long> select = criteria.select(cb.countDistinct(relationship));
    ///*w  w w  . ja v a  2  s .  c o m*/
    select.where(buildPredicateFilter(cb, receiver, relationship));
    //
    return em.createQuery(select);
}

From source file:org.broadleafcommerce.cms.admin.server.handler.PageItemCriteriaCustomPersistenceHandler.java

@Override
public void remove(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao,
        RecordHelper helper) throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    try {//from w  w  w.j  a v a 2 s. c  o  m
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        Map<String, FieldMetadata> adminProperties = helper
                .getSimpleMergedProperties(PageItemCriteria.class.getName(), persistencePerspective);
        Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
        PageItemCriteria adminInstance = (PageItemCriteria) dynamicEntityDao
                .retrieve(Class.forName(entity.getType()[0]), primaryKey);

        if (adminInstance.getPage().getLockedFlag()) {
            /*
            This may be an attempt to delete a target item criteria off an otherwise un-edited, production StructuredContent instance
             */
            CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
            CriteriaQuery<Page> query = criteriaBuilder.createQuery(Page.class);
            Root<PageImpl> root = query.from(PageImpl.class);
            query.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("archivedFlag"), Boolean.FALSE),
                    criteriaBuilder.equal(root.get("originalPageId"), adminInstance.getPage().getId())));
            query.select(root);
            TypedQuery<Page> scQuery = dynamicEntityDao.getStandardEntityManager().createQuery(query);
            try {
                Page myContent = scQuery.getSingleResult();
                for (PageItemCriteria itemCriteria : myContent.getQualifyingItemCriteria()) {
                    if (itemCriteria.getOrderItemMatchRule().equals(adminInstance.getOrderItemMatchRule())
                            && itemCriteria.getQuantity().equals(adminInstance.getQuantity())) {
                        myContent.getQualifyingItemCriteria().remove(itemCriteria);
                        return;
                    }
                }
                throw new RuntimeException("Unable to find an item criteria to delete");
            } catch (Exception e) {
                throw new IllegalArgumentException("Unable to update a locked record");
            }
        }

        dynamicEntityDao.remove(adminInstance);
    } catch (Exception e) {
        LOG.error("Unable to execute persistence activity", e);
        throw new ServiceException("Unable to remove entity for " + entity.getType()[0], e);
    }
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private Product getProduct_Mercifully() {
    return transactionTemplate.execute(new TransactionCallback<Product>() {
        @Override//from w  w  w. j  a  va2s.c o  m
        public Product doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Product> productRoot = query.from(Product.class);
            Join<Product, WarehouseProductInfo> warehouseProductInfoJoin = productRoot
                    .join(Product_.warehouseProductInfo);

            query.select(productRoot).where(cb.and(cb.equal(productRoot.get(Product_.code), "tvCode"),
                    cb.gt(warehouseProductInfoJoin.get(WarehouseProductInfo_.quantity), 50)));
            return entityManager.createQuery(query).getSingleResult();
        }
    });
}

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

/**
 * find tests associated with this artifact
 *///from   www  .  j  a  va 2 s  . com
private List<RequirementTest> findRequirementTests(Requirement requirement) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<RequirementTest> c = cb.createQuery(RequirementTest.class);
    Root<RequirementTest> obj = c.from(RequirementTest.class);
    c.select(obj).where(cb.equal(obj.get("requirement"), requirement));
    return em.createQuery(c).getResultList();
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java

@Override
public void afterPropertiesSet() throws Exception {
    this.findAllMarketPlaceRating = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>() {
                @Override/*from  w  ww .j a v  a 2 s  . co m*/
                public CriteriaQuery<MarketplaceRatingImpl> apply(CriteriaBuilder input) {
                    final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input
                            .createQuery(MarketplaceRatingImpl.class);
                    final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery
                            .from(MarketplaceRatingImpl.class);
                    criteriaQuery.select(definitionRoot);
                    return criteriaQuery;
                }
            });
}