Example usage for javax.persistence EntityManager getCriteriaBuilder

List of usage examples for javax.persistence EntityManager getCriteriaBuilder

Introduction

In this page you can find the example usage for javax.persistence EntityManager getCriteriaBuilder.

Prototype

public CriteriaBuilder getCriteriaBuilder();

Source Link

Document

Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.

Usage

From source file:net.navasoft.madcoin.backend.model.controller.helper.impl.JPAHelper.java

/**
 * Gets the quantity.// www .j a v a 2  s .  c o  m
 * 
 * @param dbAccess
 *            the db access
 * @param target
 *            the target
 * @return the quantity
 * @since 28/08/2014, 11:20:27 PM
 */
public int getQuantity(EntityManager dbAccess, Class<Entity> target) {
    CriteriaQuery<Long> cq = dbAccess.getCriteriaBuilder().createQuery(Long.class);
    Root<Entity> rt = cq.from(target);
    cq.select(dbAccess.getCriteriaBuilder().count(rt));
    Query q = dbAccess.createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
}

From source file:net.navasoft.madcoin.backend.model.controller.helper.impl.JPAHelper.java

/**
 * Find entities./*w w  w. j a v a2  s .c  o  m*/
 * 
 * @param em
 *            the em
 * @param target
 *            the target
 * @param all
 *            the all
 * @param maxResults
 *            the max results
 * @param firstResult
 *            the first result
 * @return the list
 * @since 28/08/2014, 11:20:27 PM
 */
private List<Entity> findEntities(EntityManager em, Class<Entity> target, boolean all, int maxResults,
        int firstResult) {
    CriteriaQuery<Entity> cq = em.getCriteriaBuilder().createQuery(target);
    cq.select(cq.from(target));
    TypedQuery<Entity> q = em.createQuery(cq);
    if (!all) {
        q.setMaxResults(maxResults);
        q.setFirstResult(firstResult);
    }
    return q.getResultList();
}

From source file:org.emau.icmvc.ganimed.epix.core.internal.PersonPreprocessedCache.java

/**
 * Load all personpreprocessed entities from database
 *
 * @param em//from w  ww .j a  va  2s  . c om
 * @return
 */
private List<PersonPreprocessed> getAllPersonPreprocessed(EntityManager em) {
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<PersonPreprocessed> criteriaQuery = criteriaBuilder.createQuery(PersonPreprocessed.class);
    Root<PersonPreprocessed> root = criteriaQuery.from(PersonPreprocessed.class);
    criteriaQuery.select(root);
    List<PersonPreprocessed> personPreprocessedList = em.createQuery(criteriaQuery).getResultList();
    return personPreprocessedList;
}

From source file:com.carser.viamais.vo.TransactionFilter.java

public Long count(final EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<Transaction> transaction = cq.from(Transaction.class);
    cq.select(cb.countDistinct((transaction)));
    cq.where(getPredicates(cb, transaction));
    return em.createQuery(cq).getSingleResult();
}

From source file:com.carser.viamais.vo.TransactionFilter.java

public List<Transaction> resultList(final EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
    Root<Transaction> transaction = cq.from(Transaction.class);
    cq.where(getPredicates(cb, transaction));
    @SuppressWarnings("rawtypes")
    Path path;/*w ww. ja  va2s .c o m*/
    switch (orderBy) {
    case CUSTOMER_NAME:
        path = transaction.get(Transaction_.car).get(Car_.model).get(Model_.name);
        break;
    case DATE:
        path = transaction.get(Transaction_.transactionDate);
        break;
    case PLATE:
        path = transaction.get(Transaction_.car).get(Car_.licensePlate);
        break;
    case TYPE:
        path = transaction.get(Transaction_.type);
        break;
    case YEAR:
        path = transaction.get(Transaction_.car).get(Car_.yearOfModel);
        break;
    default:
        path = transaction.get(Transaction_.car).get(Car_.model).get(Model_.name);
        break;
    }
    switch (order) {
    case DESC:
        cq.orderBy(cb.desc(path));
        break;
    default:
        cq.orderBy(cb.asc(path));
        break;
    }
    TypedQuery<Transaction> query = em.createQuery(cq);
    query.setFirstResult(offset);
    query.setMaxResults(limit);
    return query.getResultList();
}

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

/**
 * @since 5.0/*from   w  ww  .  j  a va  2  s. c o  m*/
 * @param marketplaceRatingPK the primary key of the entity you want
 * @return Set of ratings per portlet definition
 */
@PortalTransactionalReadOnly
@OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
public Set<IMarketplaceRating> getRatingsByFname(String fname) {

    //Build criteria to fetch MarketplaceRatingImpl based on the incoming portlet name. 
    final EntityManager entityManager = this.getEntityManager();
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    final CriteriaQuery<IMarketplaceRating> getByPortlet = cb.createQuery(IMarketplaceRating.class);
    final Root<MarketplaceRatingImpl> imr = getByPortlet.from(MarketplaceRatingImpl.class);
    getByPortlet.select(imr);

    //Define the path to the portlet fName
    final Path<MarketplaceRatingPK> mrPK = imr.get("marketplaceRatingPK");
    final Path<PortletDefinitionImpl> mrIPD = mrPK.get("portletDefinition");

    final ParameterExpression<String> portletFName = cb.parameter(String.class, "portletFName");

    getByPortlet.where(cb.equal(mrIPD.get("fname"), portletFName));
    TypedQuery<IMarketplaceRating> tq = entityManager.createQuery(getByPortlet);
    tq.setParameter("portletFName", fname);
    List<IMarketplaceRating> resultList = tq.getResultList();
    Set<IMarketplaceRating> resultSet = new HashSet<IMarketplaceRating>(resultList);
    return resultSet;

}

From source file:org.apache.ranger.service.XTrxLogService.java

public Long searchXTrxLogsCount(SearchCriteria searchCriteria) {
    EntityManager em = daoMgr.getEntityManager();
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<VXXTrxLog> selectCQ = criteriaBuilder.createQuery(VXXTrxLog.class);
    Root<VXXTrxLog> rootEntityType = selectCQ.from(VXXTrxLog.class);
    Predicate predicate = generatePredicate(searchCriteria, em, criteriaBuilder, rootEntityType);

    CriteriaQuery<Long> countCQ = criteriaBuilder.createQuery(Long.class);
    countCQ.select(criteriaBuilder.count(rootEntityType)).where(predicate);
    List<Long> countList = em.createQuery(countCQ).getResultList();
    Long count = 0L;// w w  w.  j  a  v  a  2  s  .  c  o m
    if (!CollectionUtils.isEmpty(countList)) {
        count = countList.get(0);
        if (count == null) {
            count = 0L;
        }
    }
    return count;
}

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

@Override
public List<ILocalAccountPerson> getPeople(LocalAccountQuery query) {
    final EntityManager entityManager = this.getEntityManager();
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb.createQuery(LocalAccountPersonImpl.class);
    final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery.from(LocalAccountPersonImpl.class);
    final CollectionJoin<LocalAccountPersonImpl, LocalAccountPersonAttributeImpl> attributes = accountRoot
            .join(LocalAccountPersonImpl_.attributes);
    final ListJoin<LocalAccountPersonAttributeImpl, String> attributeValues = attributes
            .join(LocalAccountPersonAttributeImpl_.values);

    //Due to the joins multiple rows are returned for each result
    criteriaQuery.distinct(true);//from   ww w  .  j  a v a  2  s  .c o  m
    criteriaQuery.select(accountRoot);

    final List<Predicate> whereParts = new LinkedList<Predicate>();
    final Map<Parameter<String>, String> params = new LinkedHashMap<Parameter<String>, String>();

    // if a username has been specified, append it to the query
    if (query.getName() != null) {
        whereParts.add(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), this.nameParameter));
        params.put(this.nameParameter, query.getName());
    }

    //Build Predicate for each attribute being queried
    int paramCount = 0;
    for (Map.Entry<String, List<String>> entry : query.getAttributes().entrySet()) {
        final List<String> values = entry.getValue();
        if (values == null) {
            continue;
        }

        //For each value create a Predicate checking the attribute name and value together
        for (final String value : values) {
            if (StringUtils.isBlank(value)) {
                continue;
            }

            //Create Parameter objects for the name and value, stick them in the params map for later use
            final ParameterExpression<String> nameParam = this.createParameterExpression(String.class,
                    "attrName" + paramCount);
            final ParameterExpression<String> valueParam = this.createParameterExpression(String.class,
                    "attrValue" + paramCount);

            params.put(nameParam, entry.getKey());
            params.put(valueParam, "%" + value.toLowerCase() + "%");

            //Build the and(eq, like) predicate and add it to the list of predicates for the where clause
            whereParts.add(cb.and(cb.equal(attributes.get(LocalAccountPersonAttributeImpl_.name), nameParam),
                    cb.like(cb.lower(attributeValues.as(String.class)), valueParam)));

            paramCount++;
        }
    }

    //Add the Predicates to the where clause
    criteriaQuery.where(cb.or(whereParts.toArray(new Predicate[whereParts.size()])));

    //Create the query
    final TypedQuery<LocalAccountPersonImpl> jpaQuery = this.createCachedQuery(criteriaQuery);

    //Add all of the stored up parameters to the query
    for (Map.Entry<Parameter<String>, String> entry : params.entrySet()) {
        final Parameter<String> parameter = entry.getKey();
        final String value = entry.getValue();
        jpaQuery.setParameter(parameter, value);
    }

    final List<LocalAccountPersonImpl> accounts = jpaQuery.getResultList();
    return new ArrayList<ILocalAccountPerson>(accounts);
}

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  . j ava 2 s .  c om*/
    select.where(buildPredicateFilter(cb, receiver, relationship));
    //
    return em.createQuery(select);
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.PersistentDocumentStoreController.java

/**
 * Gets all UUIDs for {@code T} type document stores owned by the given owner.
 * @param em the {@link EntityManager} to use.
 * @param ownerId the ID of the owner.//w  w w .  j a va2s  . co  m
 * @param entityClass the specific type of document stores to be retrieved; must be annotated with the {@link Entity} annotation.
 * @return a {@link List} containing {@link String} representations of the UUIDs.
 */
public <T extends PersistentDocumentStore> List<String> getAllUuids(EntityManager em, String ownerId,
        Class<T> entityClass) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(ownerId, CannedMessages.NULL_ARGUMENT, "ownerId");
    Validate.notNull(entityClass, CannedMessages.NULL_ARGUMENT, "entityClass");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<byte[]> cq = cb.createQuery(byte[].class);
    Root<T> store = cq.from(entityClass);
    cq.multiselect(store.get("id"))
            .where(cb.equal(store.get("ownerId"), cb.parameter(String.class, "ownerId")));
    TypedQuery<byte[]> tq = em.createQuery(cq);
    tq.setParameter("ownerId", ownerId);
    return Lists.newArrayList(Iterables.transform(tq.getResultList(), UuidUtils.uuidBytesToStringFunction()));
}