Example usage for javax.persistence.criteria Predicate getExpressions

List of usage examples for javax.persistence.criteria Predicate getExpressions

Introduction

In this page you can find the example usage for javax.persistence.criteria Predicate getExpressions.

Prototype

List<Expression<Boolean>> getExpressions();

Source Link

Document

Return the top-level conjuncts or disjuncts of the predicate.

Usage

From source file:com.goodhuddle.huddle.repository.TagSpecification.java

public static Specification<Tag> search(final Huddle huddle, final SearchTagsRequest request) {
    return new Specification<Tag>() {
        @Override//w  w  w . ja va 2  s. c o  m
        public Predicate toPredicate(Root<Tag> tag, CriteriaQuery<?> query, CriteriaBuilder builder) {

            Predicate conjunction = builder.conjunction();
            conjunction.getExpressions().add(builder.equal(tag.get("huddle"), huddle));

            if (StringUtils.isNotBlank(request.getName())) {
                String nameTerm = "%" + request.getName().toLowerCase() + "%";
                conjunction.getExpressions()
                        .add(builder.like(builder.lower(tag.<String>get("name")), nameTerm));
            }

            return conjunction;
        }
    };
}

From source file:com.goodhuddle.huddle.repository.BlogPostSpecification.java

public static Specification<BlogPost> search(final Huddle huddle, final SearchBlogPostRequest request) {
    return new Specification<BlogPost>() {
        @Override//from  ww w. j  a  v a 2  s .c  o m
        public Predicate toPredicate(Root<BlogPost> blogPost, CriteriaQuery<?> query, CriteriaBuilder builder) {

            Predicate conjunction = builder.conjunction();
            conjunction.getExpressions().add(builder.equal(blogPost.get("huddle"), huddle));

            if (StringUtils.isNotBlank(request.getPhrase())) {
                String phrase = "%" + request.getPhrase().toLowerCase() + "%";
                conjunction.getExpressions()
                        .add(builder.like(builder.lower(blogPost.<String>get("title")), phrase));
            }

            if (CollectionUtils.isNotEmpty(request.getBlogIds())) {
                Join<Object, Object> blog = blogPost.join("blog");
                conjunction.getExpressions().add(builder.in(blog.get("id")).value(request.getBlogIds()));
            }

            if (!request.isIncludeUnpublished()) {
                conjunction.getExpressions()
                        .add(builder.lessThan((Expression) blogPost.get("publishedOn"), new DateTime()));
            }

            return conjunction;
        }
    };
}

From source file:com.goodhuddle.huddle.repository.MemberSpecification.java

public static Specification<Member> search(final Huddle huddle, final SearchMembersRequest request) {
    return new Specification<Member>() {
        @Override//from  w  w w  .  jav a 2 s .c o  m
        public Predicate toPredicate(Root<Member> member, CriteriaQuery<?> query, CriteriaBuilder builder) {

            Predicate conjunction = builder.conjunction();

            // huddle
            conjunction.getExpressions().add(builder.equal(member.get("huddle"), huddle));

            // keywords

            if (StringUtils.isNotBlank(request.getKeywords())) {
                String[] terms = StringUtils.split(request.getKeywords());
                for (String keyword : terms) {
                    if (keyword != null && keyword.length() > 0) {

                        String matchTerm = "%" + keyword.toLowerCase() + "%";
                        conjunction.getExpressions().add(builder.or(
                                builder.like(builder.lower(member.<String>get("username")), matchTerm),
                                builder.like(builder.lower(member.<String>get("email")), matchTerm),
                                builder.like(builder.lower(member.<String>get("firstName")), matchTerm),
                                builder.like(builder.lower(member.<String>get("lastName")), matchTerm)));
                    }
                }
            }

            // security groups

            if (CollectionUtils.isNotEmpty(request.getSecurityGroupIds())) {

                Join<Object, Object> securityGroup = member.join("securityGroup",
                        request.isIncludeNoAccess() ? JoinType.LEFT : JoinType.INNER);

                Predicate disjunction = builder.disjunction();
                for (Long id : request.getSecurityGroupIds()) {
                    disjunction.getExpressions().add(builder.equal(securityGroup.get("id"), id));
                }
                if (request.isIncludeNoAccess()) {
                    disjunction.getExpressions().add(builder.isNull(securityGroup.get("id")));
                }
                conjunction.getExpressions().add(disjunction);

            } else if (request.isIncludeNoAccess()) {

                conjunction.getExpressions().add(builder.isNull(member.get("securityGroup")));

            }

            // tags

            MemberTagFilter tagFilter = request.getTags();
            if (tagFilter != null) {

                if (tagFilter.getIncluded() != null) {

                    if (CollectionUtils.isNotEmpty(tagFilter.getIncluded().getTagIds())) {

                        MemberTagFilter.TagSet included = request.getTags().getIncluded();
                        MatchType matchType = included.getMatchType();
                        Predicate tagPredicate = matchType.equals(MatchType.all) ? builder.conjunction()
                                : builder.disjunction();

                        for (Long tagId : included.getTagIds()) {
                            Subquery<Member> sq = query.subquery(Member.class);
                            Root<Member> subMember = sq.from(Member.class);
                            Join<Member, Tag> tag = subMember.join("tags");
                            sq.select(subMember).where(builder.equal(tag.get("id"), tagId));
                            tagPredicate.getExpressions().add(builder.in(member).value(sq));
                        }

                        conjunction.getExpressions().add(tagPredicate);
                    }
                }

                if (tagFilter.getExcluded() != null) {

                    if (CollectionUtils.isNotEmpty(tagFilter.getExcluded().getTagIds())) {

                        MemberTagFilter.TagSet excluded = request.getTags().getExcluded();
                        MatchType matchType = excluded.getMatchType();
                        Predicate tagPredicate = matchType.equals(MatchType.all) ? builder.disjunction()
                                : builder.conjunction();

                        for (Long tagId : excluded.getTagIds()) {
                            Subquery<Member> sq = query.subquery(Member.class);
                            Root<Member> subMember = sq.from(Member.class);
                            Join<Member, Tag> tag = subMember.join("tags");
                            sq.select(subMember).where(builder.equal(tag.get("id"), tagId));
                            tagPredicate.getExpressions().add(builder.in(member).value(sq).not());
                        }

                        conjunction.getExpressions().add(tagPredicate);
                    }
                }

            }

            return conjunction;
        }
    };
}

From source file:com.impetus.kundera.persistence.CriteriaQueryTranslator.java

/**
 * Method to translate criteriaQuery into JPQL.
 * /*from w  ww .  ja v a 2  s.c o m*/
 * @param criteriaQuery
 *            criteria query.
 * 
 * @return JPQL string.
 */
static <S> String translate(CriteriaQuery criteriaQuery) {
    QueryBuilder builder = new CriteriaQueryTranslator.QueryBuilder();

    // validate if criteria query is valid

    /**
     * select, from clause is mandatory
     * 
     * multiple from clause not support where clause is optional
     * 
     */

    Selection<S> select = criteriaQuery.getSelection();

    if (select != null) {
        builder.appendSelectClause();

    }

    if (select.getClass().isAssignableFrom(DefaultCompoundSelection.class)
            && ((CompoundSelection) select).isCompoundSelection()) {
        List<Selection<?>> selections = ((CompoundSelection) select).getCompoundSelectionItems();
        builder.appendMultiSelect(selections);
    } else if (select instanceof AggregateExpression) {
        builder.appendAggregate(((AggregateExpression) select).getAggregation());
    } else {
        String alias = select.getAlias();

        if (!StringUtils.isEmpty(alias)) {
            builder.appendAlias(alias);
        }

        Attribute attribute = ((DefaultPath) select).getAttribute();

        if (attribute != null) {
            builder.appendAttribute(attribute);
        }
    }
    Class<? extends S> clazzType = select.getJavaType();

    Set<Root<?>> roots = criteriaQuery.getRoots();

    Root<?> from = roots.iterator().next();

    Class entityClazz = from.getJavaType();

    builder.appendFromClause();

    // select.alias(paramString)
    builder.appendFrom(entityClazz);
    builder.appendAlias(from.getAlias() != null ? from.getAlias() : select.getAlias());
    Predicate where = criteriaQuery.getRestriction(); // this could be null.
    if (where != null) {
        builder.appendWhereClause();
        List<Expression<Boolean>> expressions = where.getExpressions();
        for (Expression expr : expressions) {
            builder.appendWhere(expr, from.getAlias());
        }

    }

    List<Order> orderings = criteriaQuery.getOrderList();

    if (orderings != null) {
        if (!orderings.isEmpty()) {
            builder.appendOrderClause(where == null);
        }

        for (Order order : orderings) {
            builder.appendAlias(from.getAlias() != null ? from.getAlias() : select.getAlias());
            builder.appendOrdering(order);
        }
    }
    return builder.getQuery();

    // check that roots has to be one. multiple clause not yet supported

}

From source file:com.samples.platform.core.SystemUserInitDao.java

/**
 * Get the {@link AuthenticationType}s out of the database.
 *
 * @param enabled//from   w  ww  .  j a  va2s  .c  o  m
 *            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 void enterSystemUser(final String contextName, final String userName, final String password,
        final String... roleNames) {
    AuthenticationType ac = this.of.createAuthenticationType();
    ac.setContext(contextName);
    ac.setEnabled(true);
    GrantedAuthorityType r;
    for (String roleName : roleNames) {
        r = this.of.createGrantedAuthorityType();
        r.setRoleName(roleName);
        ac.getGrantedAuthority().add(r);
    }
    ac.setPassword(password);
    ac.setUserName(userName);
    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), contextName));
    ands.getExpressions().add(cb.equal(c.<String>get(AuthenticationType_.userName), userName));
    q.where(ands);
    q.orderBy(cb.asc(c.<String>get(AuthenticationType_.userName)));
    TypedQuery<AuthenticationType> typedQuery = this.em.createQuery(q);
    try {
        AuthenticationType stored = typedQuery.getSingleResult();
        if (stored != null) {
            this.em.persist(ac);
        }
    } catch (NoResultException e) {
        this.em.persist(ac);
    }
}

From source file:com.github.dactiv.orm.core.spring.data.jpa.restriction.PredicateMultipleValueSupport.java

public Predicate build(PropertyFilter filter, SpecificationEntity entity) {
    Object value = convertMatchValue(filter.getMatchValue(), filter.getFieldType());
    Predicate predicate = null;/*from   w  w w  .j a va2s  .  c o m*/

    if (filter.hasMultiplePropertyNames()) {
        Predicate orDisjunction = entity.getBuilder().disjunction();
        for (String propertyName : filter.getPropertyNames()) {
            orDisjunction.getExpressions().add(build(propertyName, value, entity));
        }
        predicate = orDisjunction;
    } else {
        predicate = build(filter.getSinglePropertyName(), value, entity);
    }

    return predicate;
}

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  w  w.j  a v a 2s  .  co m
 *            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.model.analysis.AnalysisDao.java

/**
 * Get the list of {@link ComplexType} with the ids.
 *
 * @param modelVersion/*  w  ww.  j av a  2s  .c  o m*/
 *            the model version.
 * @param ids
 *            the list of ids to return.
 * @return the list of {@link ComplexType}.
 * @since 3.5.1
 */
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<ComplexType> getComplexTypesById(final String modelVersion, final List<String> ids) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<ComplexType> q = cb.createQuery(ComplexType.class);
    final Root<ComplexType> f = q.from(ComplexType.class);
    final Predicate orIds = cb.disjunction();
    ids.stream().forEach(id -> orIds.getExpressions().add(cb.equal(f.<String>get(ComplexType_.id), id)));
    q.where(cb.equal(f.<String>get(ComplexType_.modelVersion), modelVersion), orIds);
    final TypedQuery<ComplexType> typedQuery = this.em.createQuery(q);
    final List<ComplexType> value = typedQuery.getResultList();
    value.stream().forEach(ct -> EagerLoader.load(ct));
    return value;
}

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

/**
 * Get the list of {@link ElementType} with the ids.
 *
 * @param modelVersion/*from www.  ja v a 2 s.  com*/
 *            the model version.
 * @param ids
 *            the list of ids to return.
 * @return the list of {@link ElementType}.
 * @since 3.5.1
 */
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<ElementType> getElementTypesById(final String modelVersion, final List<String> ids) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<ElementType> q = cb.createQuery(ElementType.class);
    final Root<ElementType> f = q.from(ElementType.class);
    final Predicate orIds = cb.disjunction();
    ids.stream().forEach(id -> orIds.getExpressions().add(cb.equal(f.<String>get(ElementType_.id), id)));
    q.where(cb.equal(f.<String>get(ElementType_.modelVersion), modelVersion), orIds);
    final TypedQuery<ElementType> typedQuery = this.em.createQuery(q);
    final List<ElementType> value = typedQuery.getResultList();
    value.stream().forEach(ct -> EagerLoader.load(ct));
    return value;
}

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

/**
 * Get the list of {@link FieldMappingType} with the ids.
 *
 * @param modelVersion//from   ww  w . java  2  s . c o m
 *            the model version.
 * @param ids
 *            the list of ids to return.
 * @return the list of {@link FieldMappingType}.
 * @since 3.5.1
 */
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<FieldMappingType> getFieldMappingTypesById(final String modelVersion, final List<String> ids) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<FieldMappingType> q = cb.createQuery(FieldMappingType.class);
    final Root<FieldMappingType> f = q.from(FieldMappingType.class);
    final Predicate orIds = cb.disjunction();
    ids.stream().forEach(id -> orIds.getExpressions().add(cb.equal(f.<String>get(FieldMappingType_.id), id)));
    q.where(cb.equal(f.<String>get(FieldMappingType_.modelVersion), modelVersion), orIds);
    final TypedQuery<FieldMappingType> typedQuery = this.em.createQuery(q);
    final List<FieldMappingType> value = typedQuery.getResultList();
    value.stream().forEach(ct -> EagerLoader.load(ct));
    return value;
}