Search in sources :

Example 46 with Predicate

use of javax.persistence.criteria.Predicate in project ice by JBEI.

the class FolderDAO method getFolderSize.

/**
     * Retrieves the count of the number of contents in the folder.
     * Currently, it is assumed that the contents of folders are only entries. The entries
     * that are counted are those that have a visibility of "OK"
     *
     * @param id          unique folder identifier
     * @param filter      optional filter for entry fields
     * @param visibleOnly if true, counts only entries with visibility "OK"
     * @return number of child contents in the folder
     */
public Long getFolderSize(long id, String filter, boolean visibleOnly) {
    try {
        CriteriaQuery<Long> query = getBuilder().createQuery(Long.class);
        Root<Folder> from = query.from(Folder.class);
        Join<Folder, Entry> entry = from.join("contents");
        ArrayList<Predicate> predicates = new ArrayList<>();
        if (filter != null && !filter.trim().isEmpty()) {
            filter = filter.toLowerCase();
            predicates.add(getBuilder().or(getBuilder().like(getBuilder().lower(entry.get("name")), "%" + filter + "%"), getBuilder().like(getBuilder().lower(entry.get("alias")), "%" + filter + "%"), getBuilder().like(getBuilder().lower(entry.get("shortDescription")), "%" + filter + "%"), getBuilder().like(getBuilder().lower(entry.get("partNumber")), "%" + filter + "%")));
        }
        if (visibleOnly) {
            predicates.add(entry.get("visibility").in(Arrays.asList(Visibility.OK.getValue(), Visibility.REMOTE.getValue())));
        }
        predicates.add(getBuilder().equal(from.get("id"), id));
        query.select(getBuilder().countDistinct(entry.get("id")));
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        return currentSession().createQuery(query).uniqueResult();
    } catch (HibernateException he) {
        Logger.error(he);
        throw new DAOException(he);
    }
}
Also used : DAOException(org.jbei.ice.storage.DAOException) HibernateException(org.hibernate.HibernateException) Predicate(javax.persistence.criteria.Predicate)

Example 47 with Predicate

use of javax.persistence.criteria.Predicate in project uPortal by Jasig.

the class JpaLocalAccountDaoImpl method getPeople.

@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);
    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);
}
Also used : ArrayList(java.util.ArrayList) Predicate(javax.persistence.criteria.Predicate) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) LinkedList(java.util.LinkedList) EntityManager(javax.persistence.EntityManager) Parameter(javax.persistence.Parameter) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 48 with Predicate

use of javax.persistence.criteria.Predicate in project uPortal by Jasig.

the class JpaMarketplaceRatingDao method getRating.

/**
 * @param marketplaceRatingPK the primary key of the entity you want
 * @return an attached entity if found, null otherwise
 */
@PortalTransactionalReadOnly
@OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
public IMarketplaceRating getRating(MarketplaceRatingPK marketplaceRatingPK) {
    final MarketplaceRatingPK tempRatingPK = marketplaceRatingPK;
    MarketplaceRatingImpl temp = new MarketplaceRatingImpl();
    temp.setMarketplaceRatingPK(marketplaceRatingPK);
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(temp)) {
        temp = entityManager.merge(temp);
        return temp;
    } else {
        final TypedQuery<MarketplaceRatingImpl> query = this.createQuery(this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>() {

            @Override
            public CriteriaQuery<MarketplaceRatingImpl> apply(CriteriaBuilder input) {
                final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input.createQuery(MarketplaceRatingImpl.class);
                final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery.from(MarketplaceRatingImpl.class);
                Predicate conditionUser = input.equal(definitionRoot.get("marketplaceRatingPK").get("userName"), tempRatingPK.getUserName());
                Predicate conditionPortlet = input.equal(definitionRoot.get("marketplaceRatingPK").get("portletDefinition"), tempRatingPK.getPortletDefinition());
                Predicate allConditions = input.and(conditionPortlet, conditionUser);
                criteriaQuery.where(allConditions);
                return criteriaQuery;
            }
        }));
        List<MarketplaceRatingImpl> results = query.getResultList();
        if (!results.isEmpty()) {
            return results.get(0);
        } else {
            return null;
        }
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Function(com.google.common.base.Function) EntityManager(javax.persistence.EntityManager) OpenEntityManager(org.apereo.portal.jpa.OpenEntityManager) Predicate(javax.persistence.criteria.Predicate) OpenEntityManager(org.apereo.portal.jpa.OpenEntityManager)

Example 49 with Predicate

use of javax.persistence.criteria.Predicate in project cxf by apache.

the class AbstractJPATypedQueryVisitor method doBuildCollectionPredicate.

@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate doBuildCollectionPredicate(ConditionType ct, Path<?> path, CollectionCheckInfo collInfo) {
    Predicate pred = null;
    Expression<Integer> exp = builder.size((Expression<? extends Collection>) path);
    Integer value = Integer.valueOf(collInfo.getCollectionCheckValue().toString());
    switch(ct) {
        case GREATER_THAN:
            pred = builder.greaterThan(exp, value);
            break;
        case EQUALS:
            pred = builder.equal(exp, value);
            break;
        case NOT_EQUALS:
            pred = builder.notEqual(exp, value);
            break;
        case LESS_THAN:
            pred = builder.lessThan(exp, value);
            break;
        case LESS_OR_EQUALS:
            pred = builder.lessThanOrEqualTo(exp, value);
            break;
        case GREATER_OR_EQUALS:
            pred = builder.greaterThanOrEqualTo(exp, value);
            break;
        default:
            break;
    }
    return pred;
}
Also used : Predicate(javax.persistence.criteria.Predicate)

Example 50 with Predicate

use of javax.persistence.criteria.Predicate in project cxf by apache.

the class AbstractJPATypedQueryVisitor method visit.

public void visit(SearchCondition<T> sc) {
    if (builder == null) {
        builder = em.getCriteriaBuilder();
        cq = builder.createQuery(queryClass);
        root = cq.from(tClass);
        predStack.push(new ArrayList<>());
    }
    if (sc.getStatement() != null) {
        predStack.peek().add(buildPredicate(sc.getStatement()));
    } else {
        predStack.push(new ArrayList<>());
        for (SearchCondition<T> condition : sc.getSearchConditions()) {
            condition.accept(this);
        }
        List<Predicate> predsList = predStack.pop();
        Predicate[] preds = predsList.toArray(new Predicate[predsList.size()]);
        Predicate newPred;
        if (sc instanceof OrSearchCondition) {
            newPred = builder.or(preds);
        } else {
            newPred = builder.and(preds);
        }
        predStack.peek().add(newPred);
    }
}
Also used : OrSearchCondition(org.apache.cxf.jaxrs.ext.search.OrSearchCondition) Predicate(javax.persistence.criteria.Predicate)

Aggregations

Predicate (javax.persistence.criteria.Predicate)59 EntityManager (javax.persistence.EntityManager)19 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)19 Test (org.junit.Test)17 AbstractMetamodelSpecificTest (org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest)11 ArrayList (java.util.ArrayList)9 Order (org.hibernate.jpa.test.metamodel.Order)8 HibernateException (org.hibernate.HibernateException)6 DAOException (org.jbei.ice.storage.DAOException)6 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)5 Root (javax.persistence.criteria.Root)5 LinkedList (java.util.LinkedList)3 List (java.util.List)3 TypedQuery (javax.persistence.TypedQuery)3 Study (com.odysseusinc.arachne.portal.model.Study)2 IdmFormAttributeDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto)2 IdmIdentityContract (eu.bcvsolutions.idm.core.model.entity.IdmIdentityContract)2 IdmIdentityRole (eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole)2 IdmRoleCatalogueRole (eu.bcvsolutions.idm.core.model.entity.IdmRoleCatalogueRole)2 IdmTreeNode (eu.bcvsolutions.idm.core.model.entity.IdmTreeNode)2