Java Code Examples for javax.persistence.criteria.CriteriaBuilder.and()

The following are Jave code examples for showing how to use and() of the javax.persistence.criteria.CriteriaBuilder class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: spring-microservice-sample   File: PostSpecifications.java   Source Code and License Vote up 11 votes
public static Specification<Post> filterByKeywordAndStatus(
    final String keyword,//
    final Post.Status status) {
    return (Root<Post> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.hasText(keyword)) {
            predicates.add(
                cb.or(
                    cb.like(root.get(Post_.title), "%" + keyword + "%"),
                    cb.like(root.get(Post_.content), "%" + keyword + "%")
                )
            );
        }

        if (status != null) {
            predicates.add(cb.equal(root.get(Post_.status), status));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
 
Example 2
Project: OperatieBRP   File: LeveringsautorisatieFilterFactory.java   Source Code and License Vote up 9 votes
@Override
public Predicate toPredicate(final Root<?> leveringsautorisatieRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Root<Dienstbundel> dienstbundelRoot = query.from(Dienstbundel.class);
    final Root<Dienst> dienstRoot = query.from(Dienst.class);

    // Join dienst op dienstbundel
    final Predicate joinPredicateDienstbundel = dienstbundelRoot.get(ID).in(dienstRoot.get("dienstbundel").get(ID));

    // Join dienst op leveringsautorisatie
    final Predicate joinPredicateLeveringsautorisatie = leveringsautorisatieRoot.get(ID).in(dienstbundelRoot.get(LEVERINGSAUTORISATIE).get(ID));

    // OntvangendePartij
    final Predicate soortDienstPredicate = cb.equal(dienstRoot.get("soortDienstId"), value);

    return cb.and(joinPredicateDienstbundel, joinPredicateLeveringsautorisatie, soortDienstPredicate);
}
 
Example 3
Project: cloud   File: ByRangeSpecification.java   Source Code and License Vote up 7 votes
@Override
public  Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();

    for (Range<T> range : ranges) {
        if (range.isSet()) {
            Predicate rangePredicate = buildRangePredicate(range, root, builder);

            if (rangePredicate != null) {
                if (!range.isIncludeNullSet() || range.getIncludeNull() == FALSE) {
                    predicates.add(rangePredicate);
                } else {
                    predicates.add(builder.or(rangePredicate, builder.isNull(root.get(range.getField()))));
                }
            }

            if (TRUE == range.getIncludeNull()) {
                predicates.add(builder.isNull(root.get(range.getField())));
            } else if (FALSE == range.getIncludeNull()) {
                predicates.add(builder.isNotNull(root.get(range.getField())));
            }
        }
    }
    return predicates.isEmpty() ? builder.conjunction() : builder.and(toArray(predicates, Predicate.class));
}
 
Example 4
Project: REST-Web-Services   File: UserSpecs.java   Source Code and License Vote up 6 votes
/**
 * Generate a criteria query predicate for a where clause based on the given parameters.
 *
 * @param root The root to use
 * @param cb The criteria builder to use
 * @param username The user's name
 * @return The specification
 */
public static Predicate getFindPredicate(
        final Root<UserEntity> root,
        final CriteriaBuilder cb,
        @Nullable final String username
) {
    final List<Predicate> predicates = new ArrayList<>();

    predicates.add(cb.isTrue(root.get(UserEntity_.enabled)));

    if (StringUtils.isNotBlank(username)) {
        predicates.add(cb.like(root.get(UserEntity_.username), "%" + username + "%"));
    }

    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
 
Example 5
Project: iotplatform   File: JpaBaseEventDao.java   Source Code and License Vote up 6 votes
private Specification<EventEntity> getEntityFieldsSpec(UUID tenantId, EntityId entityId, String eventType) {
    return new Specification<EventEntity>() {
        @Override
        public Predicate toPredicate(Root<EventEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (tenantId != null) {
                Predicate tenantIdPredicate = criteriaBuilder.equal(root.get("tenantId"), UUIDConverter.fromTimeUUID(tenantId));
                predicates.add(tenantIdPredicate);
            }
            if (entityId != null) {
                Predicate entityTypePredicate = criteriaBuilder.equal(root.get("entityType"), entityId.getEntityType());
                predicates.add(entityTypePredicate);
                Predicate entityIdPredicate = criteriaBuilder.equal(root.get("entityId"), UUIDConverter.fromTimeUUID(entityId.getId()));
                predicates.add(entityIdPredicate);
            }
            if (eventType != null) {
                Predicate eventTypePredicate = criteriaBuilder.equal(root.get("eventType"), eventType);
                predicates.add(eventTypePredicate);
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[]{}));
        }
    };
}
 
Example 6
Project: datatable-java   File: DatatableSpecification.java   Source Code and License Vote up 6 votes
private Predicate getPredicateGlobalSearch(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder cb,
    Predicate predicate) {
    // check whether a global filter value exists
    final String globalFilterValue = input.getSearch().getValue();
    if (globalFilterValue != null && globalFilterValue.trim().length() > 0) {
        LOGGER.fine("filtre global: {"+ globalFilterValue+"}");

        Predicate matchOneColumnPredicate = cb.disjunction();
        // add a 'WHERE .. LIKE' clause on each searchable column
        for (final DatatableColumn column : input.getColumns()) {
            if (column.getSearchable()) {
                LOGGER.log(Level.FINE, "filtre global pour colonne: {}", column);
                final Expression<String> expression = DatatableHelper.getExpression(root, column.getData(), String.class);

                matchOneColumnPredicate = cb.or(matchOneColumnPredicate,
                    cb.like(cb.lower(expression), getLikeFilterValue(globalFilterValue), ESCAPE_CHAR));
            }
        }
        predicate = cb.and(predicate, matchOneColumnPredicate);
    }
    return predicate;
}
 
Example 7
Project: spring-repository-plus   File: SpecificationImpl.java   Source Code and License Vote up 6 votes
@Override
public Predicate toPredicate(Root<Object> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<>();
    for(Specification specification: specifications){
        Predicate p = specification.toPredicate(root, cq, cb);
        if(p!=null)
            predicates.add(p);
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
 
Example 8
Project: bookshelf   File: BookSpecification.java   Source Code and License Vote up 6 votes
@Override
public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<>();

    String title = criteria.getTitle();
    if (Objects.nonNull(title) && !title.isEmpty()) {
        predicates.add(cb.like(cb.lower(root.get(CONST_TITLE)), "%" + title.trim().toLowerCase() + "%"));
    }

    int year = criteria.getYear();
    if (Objects.nonNull(year) && year > 0) {
        predicates.add(cb.equal(root.<Integer>get(CONST_YEAR), year));
    }

    String author = criteria.getAuthor();
    if (Objects.nonNull(author) && !author.isEmpty()) {
        predicates.add(cb.like(cb.lower(root.get(CONST_AUTHOR)), "%" + author.trim().toLowerCase() + "%"));
    }

    return cb.and(predicates.toArray(new Predicate[0]));
}
 
Example 9
Project: OperatieBRP   File: LeveringsautorisatieFilterFactory.java   Source Code and License Vote up 6 votes
@Override
public Predicate toPredicate(final Root<?> leveringsautorisatieRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Root<Dienstbundel> dienstbundelRoot = query.from(Dienstbundel.class);

    // Join dienst op leveringsautorisatie
    final Predicate joinPredicateLeveringsautorisatie = leveringsautorisatieRoot.get(ID).in(dienstbundelRoot.get(LEVERINGSAUTORISATIE).get(ID));

    // Dienstbundel
    final Expression<String> attributeExpression = cb.lower(cb.function(UNACCENT, String.class, dienstbundelRoot.get("naam")));
    final Expression<String> valueExpression =
            cb.lower(
                    cb.function(
                            UNACCENT,
                            String.class,
                            cb.concat(cb.concat(cb.literal(WILDCARD), cb.literal(value.toString())), cb.literal(WILDCARD))));
    final Predicate dienstBundelPredicate = cb.like(attributeExpression, valueExpression);

    return cb.and(joinPredicateLeveringsautorisatie, dienstBundelPredicate);
}
 
Example 10
Project: C4SG-Obsolete   File: UserSpecification.java   Source Code and License Vote up 5 votes
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
    Predicate resultPredicate = null;
    List<Predicate> predicates = buildPredicates(root, cb);
    if (!predicates.isEmpty()) {
        resultPredicate = cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }

    return resultPredicate;
}
 
Example 11
Project: REST-Web-Services   File: ContributionSpecs.java   Source Code and License Vote up 5 votes
/**
 * Generate a criteria query predicate for a where clause based on the given parameters.
 *
 * @param root The root to use
 * @param cb The criteria builder to use
 * @param movie The MovieEntity object
 * @param field The movie field
 * @param status The contribution status
 * @param fromDate Creation date range "from"
 * @param toDate Creation date range "to"
 * @return The specification
 */
public static Predicate getFindPredicate(
        final Root<ContributionEntity> root,
        final CriteriaBuilder cb,
        @Nullable final MovieEntity movie,
        @Nullable final MovieField field,
        @Nullable final DataStatus status,
        @Nullable final Date fromDate,
        @Nullable final Date toDate
) {
    final List<Predicate> predicates = new ArrayList<>();

    if (Optional.ofNullable(movie).isPresent()) {
        predicates.add(cb.equal(root.get(ContributionEntity_.movie), movie));
    }
    if (Optional.ofNullable(field).isPresent()) {
        predicates.add(cb.equal(root.get(ContributionEntity_.field), field));
    }
    if (Optional.ofNullable(status).isPresent()) {
        predicates.add(cb.equal(root.get(ContributionEntity_.status), status));
    }
    if (fromDate != null) {
        predicates.add(cb.greaterThanOrEqualTo(root.get(ContributionEntity_.created), fromDate));
    }
    if (toDate != null) {
        predicates.add(cb.lessThanOrEqualTo(root.get(ContributionEntity_.created), toDate));
    }

    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
 
Example 12
Project: bootstrap   File: DynamicSpecification.java   Source Code and License Vote up 5 votes
/**
 * Create a predicate group.
 */
private Predicate getGroupPredicate(final UiFilter group, final Root<U> root, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
	// Build the predicates
	final java.util.List<Predicate> predicates = getPredicates(group, root, query, cb);

	// Build the specification
	if (predicates.isEmpty()) {
		return cb.conjunction();
	}
	final Predicate[] filteredPredicates = predicates.toArray(new Predicate[predicates.size()]);
	if (group.getGroupOp() == FilterOperator.AND) {
		return cb.and(filteredPredicates);
	}
	return cb.or(filteredPredicates);
}
 
Example 13
Project: OperatieBRP   File: PersoonFilterFactory.java   Source Code and License Vote up 5 votes
@Override
public Predicate toPredicate(final Root<?> persoonRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Root<PersoonAdres> persoonAdressenRoot = query.from(PersoonAdres.class);
    final Predicate joinPredicateAdressen = persoonRoot.get(ID).in(persoonAdressenRoot.get(PERSOON).get(ID));

    final Expression<String> attributeExpression1 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel1")));
    final Expression<String> attributeExpression2 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel2")));
    final Expression<String> attributeExpression3 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel3")));
    final Expression<String> attributeExpression4 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel4")));
    final Expression<String> attributeExpression5 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel5")));
    final Expression<String> attributeExpression6 =
            cb.lower(cb.function(UNACCENT, String.class, persoonAdressenRoot.get("buitenlandsAdresRegel6")));
    final Expression<String> valueExpression =
            cb.lower(
                    cb.function(
                            UNACCENT,
                            String.class,
                            cb.concat(cb.concat(cb.literal(WILDCARD), cb.literal(value.toString())), cb.literal(WILDCARD))));
    final Predicate adresPredicate1 = cb.like(attributeExpression1, valueExpression);
    final Predicate adresPredicate2 = cb.like(attributeExpression2, valueExpression);
    final Predicate adresPredicate3 = cb.like(attributeExpression3, valueExpression);
    final Predicate adresPredicate4 = cb.like(attributeExpression4, valueExpression);
    final Predicate adresPredicate5 = cb.like(attributeExpression5, valueExpression);
    final Predicate adresPredicate6 = cb.like(attributeExpression6, valueExpression);

    final Predicate buitenlandsAdres = cb.or(adresPredicate1, adresPredicate2, adresPredicate3, adresPredicate4, adresPredicate5, adresPredicate6);
    return cb.and(joinPredicateAdressen, buitenlandsAdres);
}
 
Example 14
Project: sctalk   File: SearchCriteria.java   Source Code and License Vote up 5 votes
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    if (!criterions.isEmpty()) {
        List<Predicate> predicates = new ArrayList<Predicate>();
        for (Criterion c : criterions) {
            predicates.add(c.toPredicate(root, query, builder));
        }
        // 将所有条件用 and 联合起来
        if (predicates.size() > 0) {
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    }
    return builder.conjunction();
}
 
Example 15
Project: datatable-java   File: DatatableSpecification.java   Source Code and License Vote up 5 votes
private Predicate getPredicateColonnes(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder cb,
    Predicate predicate) {
    // check for each searchable column whether a filter value exists
    for (final DatatableColumn column : input.getColumns()) {
        final boolean isColumnSearchable =
            column.getSearchable() && column.getSearch() != null
                && hasText(column.getSearch().getValue());
        if (!isColumnSearchable) {
            continue;
        }

        LOGGER.fine("colonne a filtrer: {"+ column+"}");

        // the filter contains only one value, add a 'WHERE .. LIKE'
        // clause
        if (isBoolean(column.getSearch().getValue())) {
            final Expression<Boolean> booleanExpression = DatatableHelper.getExpression(root, column.getData(), Boolean.class);
            predicate =
                cb.and(predicate, cb.equal(booleanExpression, Boolean.valueOf(column.getSearch().getValue())));
        } else {
            final Expression<String> stringExpression = DatatableHelper.getExpression(root, column.getData(), String.class);
            predicate = cb.and(predicate, cb.like(cb.lower(stringExpression),
                getLikeFilterValue(column.getSearch().getValue()), ESCAPE_CHAR));
        }

    }
    return predicate;
}
 
Example 16
Project: OperatieBRP   File: AdministratieveHandelingFilterFactory.java   Source Code and License Vote up 5 votes
@Override
public Predicate toPredicate(final Root<?> administratieveHandelingRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Root<PersoonAfgeleidAdministratiefHistorie> persoonHistoryRoot = query.from(PersoonAfgeleidAdministratiefHistorie.class);

    // Join persoon
    final Predicate joinPredicate = administratieveHandelingRoot.get(ID).in(persoonHistoryRoot.get(ADMINISTRATIEVE_HANDELING).get(ID));

    // Bsn
    final Predicate bsnPredicate = cb.equal(persoonHistoryRoot.get(PERSOON).get(ADMINISTRATIE_NUMMER), value);

    return cb.and(bsnPredicate, joinPredicate);
}
 
Example 17
Project: OperatieBRP   File: AdministratieveHandelingFilterFactory.java   Source Code and License Vote up 5 votes
@Override
public Predicate toPredicate(final Root<?> administratieveHandelingRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Root<PersoonAfgeleidAdministratiefHistorie> persoonHistoryRoot = query.from(PersoonAfgeleidAdministratiefHistorie.class);

    // Join persoon
    final Predicate joinPredicate = administratieveHandelingRoot.get(ID).in(persoonHistoryRoot.get(ADMINISTRATIEVE_HANDELING).get(ID));

    // Bsn
    final Predicate bsnPredicate = cb.equal(persoonHistoryRoot.get(PERSOON).get(BURGERSERVICE_NUMMER), value);

    return cb.and(bsnPredicate, joinPredicate);
}
 
Example 18
Project: c4sg-services   File: UserSpecification.java   Source Code and License Vote up 5 votes
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
    Predicate resultPredicate = null;
    List<Predicate> predicates = buildPredicates(root, cb);
    if (!predicates.isEmpty()) {
        resultPredicate = cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }

    return resultPredicate;
}
 
Example 19
Project: OperatieBRP   File: LeveringsautorisatieFilterFactory.java   Source Code and License Vote up 5 votes
@Override
public Predicate toPredicate(final Root<?> leveringsautorisatieRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final Root<ToegangLeveringsAutorisatie> toegangLeveringsAutorisaties = query.from(ToegangLeveringsAutorisatie.class);
    final Predicate joinPredicateToegangLeveringsAutorisatie =
            leveringsautorisatieRoot.get(ID).in(toegangLeveringsAutorisaties.get(LEVERINGSAUTORISATIE).get(ID));
    final Predicate geautoriseerdePredicate = cb.equal(toegangLeveringsAutorisaties.get(field), value);
    return cb.and(joinPredicateToegangLeveringsAutorisatie, geautoriseerdePredicate);
}
 
Example 20
Project: aws-photosharing-example   File: ServiceFacade.java   Source Code and License Vote up 4 votes
public synchronized <T> ListResponse<T> list(ListRequest<T> p_request) {		 		 	

  	CriteriaBuilder builder = em().getCriteriaBuilder();

  	CriteriaQuery<T> search = builder.createQuery(p_request.getType());		
CriteriaQuery<Long> count = builder.createQuery(Long.class);

Root<T> root = search.from(p_request.getType());			
		
count.select(builder.count(root));
count.from(p_request.getType());

search.select(root);								

Predicate or_predicate = getFilterPredicate(builder::or, root, builder, p_request.getORFilter());
Predicate and_predicate = getFilterPredicate(builder::and, root, builder, p_request.getANDFilter());	
Predicate member_predicate = getIsMemberOfPredicate(root, builder, p_request.getMemberFilter());
Predicate filter_predicate = null;							

if (and_predicate != null && or_predicate != null)
	filter_predicate = builder.and(and_predicate, or_predicate);
else if (and_predicate != null)
	filter_predicate = and_predicate;
else if (or_predicate != null)
	filter_predicate = or_predicate;	
if (member_predicate != null) {
	if  (filter_predicate != null)
		filter_predicate = builder.and(filter_predicate, member_predicate);
	else
		filter_predicate = member_predicate;					
}


if (filter_predicate != null) {
	search.where(filter_predicate);
	count.where(filter_predicate);
}					

List<Order> order = getSort(root,  builder,  p_request.getSort());

if (order.size() > 0) {
	search.orderBy(order);
}
	

List<T> results = em().createQuery(search)
	.setHint("org.hibernate.cacheable", p_request.getCachable())
	.setFirstResult(p_request.getFirst())
	.setMaxResults(p_request.getMax())				
	.getResultList();					

Long total = em().createQuery(count)
				.setHint("org.hibernate.cacheable", p_request.getCachable())
				.getSingleResult();					
						
done();

return new ListResponse<T>(results, p_request.getFirst(), p_request.getMax(), total.intValue());
  }