Java 类javax.persistence.criteria.Predicate 实例源码

项目:spring-microservice-sample    文件:UserSpecifications.java   
public static Specification<User> byKeyword(String keyword, String role, String active){
    return (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {

        List<Predicate> predicates = new ArrayList<>();

        if (StringUtils.hasText(keyword)) {
            predicates.add(
                cb.or(
                    cb.like(root.get(User_.email), "%" + keyword + "%"),
                    cb.like(root.get(User_.username), "%" + keyword + "%")
                ));
        }

        if (StringUtils.hasText(role) && !"ALL".equals(role)) {

            ListJoin<User, String> roleJoin = root.join(User_.roles);
            predicates.add(cb.equal(roleJoin, role));
        }
        if (StringUtils.hasText(active)) {
            predicates.add(cb.equal(root.get(User_.active), Boolean.valueOf(active)));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
项目:owl    文件:TestSuiteFilterSpecification.java   
@Override
public Predicate toPredicate(Root<TestSuite> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    Predicate result = null;

    if (StringUtils.isNotEmpty(filter.getSuite())) {
        result = criteriaBuilder.like(criteriaBuilder.lower(root.get(SUITE_PROPERTY)),
                buildLikeValue(filter.getSuite()));
    }

    return result;
}
项目:spring-microservice-sample    文件:PostSpecifications.java   
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()]));
    };
}
项目:otus_java_2017_10    文件:ConnectionHelper.java   
private static void _criteria(DbService dbService) {
    final EntityManager em = dbService.getEntityManager();

    // INSERT new record
    em.getTransaction().begin();
    em.persist(new Account("A"));
    em.persist(new Account("B"));
    em.persist(new Account("C"));
    em.getTransaction().commit();



    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Account> query = builder.createQuery(Account.class);
    Root<Account> acc = query.from(Account.class);

    Predicate cond = builder.gt(acc.get("id"), 1);
    query.where(cond);
    TypedQuery<Account> q = em.createQuery(query);
    List<Account> resultList = q.getResultList();
    System.out.println(resultList);


}
项目:sucok-framework    文件:NotIn.java   
@Override
public Predicate buildJpaPredicate(CriteriaBuilder builder, Root<?> root) {
    Expression<Object> path = QueryFormHelper.getPath(root, field);
    CriteriaBuilder.In<Object> predicate = builder.in(path);
    int length = Array.getLength(value);
    for (int i = 0; i < length; i++) {
        predicate.value(Array.get(value, i));
    }
    return builder.not(predicate);
}
项目:OperatieBRP    文件:LeveringsautorisatieFilterFactory.java   
@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);
}
项目:REST-Web-Services    文件:MessageSpecs.java   
/**
 * Get a specification using the specified parameters.
 *
 * @param user The sender's user
 * @param subject The subject of the message
 * @param text The text of the message
 * @return The specification
 */
public static Specification<MessageEntity> findSentMessagesForUser(
        final UserEntity user,
        @Nullable final String subject,
        @Nullable final String text
) {
    return (final Root<MessageEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();

        predicates.add(cb.equal(root.get(MessageEntity_.sender), user));

        if (Optional.ofNullable(subject).isPresent()) {
            predicates.add(cb.like(root.get(MessageEntity_.subject), "%" + subject + "%"));
        }
        if (Optional.ofNullable(text).isPresent()) {
            predicates.add(cb.like(root.get(MessageEntity_.text), "%" + text + "%"));
        }

        predicates.add(cb.isTrue(root.get(MessageEntity_.isVisibleForSender)));

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
项目:REST-Web-Services    文件:MessageSpecs.java   
/**
 * Get a specification using the specified parameters.
 *
 * @param user The recipient's user
 * @param subject The subject of the message
 * @param text The text of the message
 * @return The specification
 */
public static Specification<MessageEntity> findReceivedMessagesForUser(
        final UserEntity user,
        @Nullable final String subject,
        @Nullable final String text
) {
    return (final Root<MessageEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();

        predicates.add(cb.equal(root.get(MessageEntity_.recipient), user));

        if (Optional.ofNullable(subject).isPresent()) {
            predicates.add(cb.like(root.get(MessageEntity_.subject), "%" + subject + "%"));
        }
        if (Optional.ofNullable(text).isPresent()) {
            predicates.add(cb.like(root.get(MessageEntity_.text), "%" + text + "%"));
        }

        predicates.add(cb.isTrue(root.get(MessageEntity_.isVisibleForRecipient)));

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
项目:coodoo-listing    文件:ListingQuery.java   
private void addToWhereConstraint(ListingPredicate listingPredicate) {
    if (listingPredicate != null) {

        Predicate predicate = null;
        List<ListingPredicate> filters = new ArrayList<>();
        Map<String, Field> fieldMap = ListingUtil.getFields(domainClass).stream().collect(Collectors.toMap(field -> field.getName(), field -> field));

        if (listingPredicate.hasPredicates()) {
            filters.addAll(listingPredicate.getPredicates());
        } else {
            filters.add(new ListingPredicate().filter(listingPredicate.getAttribute(), listingPredicate.getFilter()));
        }
        predicate = filterByPredicateTree(listingPredicate.isDisjunctive(), listingPredicate.isNegation(), filters, fieldMap);

        if (predicate != null) {
            if (listingPredicate.isNegation()) {
                predicate = criteriaBuilder.not(predicate);
            }
            whereConstraints.add(predicate);
        }
    }
}
项目:owl    文件:TestRunFilterSpecification.java   
@Override
public Predicate toPredicate(Root<TestRun> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    Predicate result = null;

    if (!CollectionUtils.isEmpty(filter.getBuilds())) {
        result = criteriaBuilder.in(root.get(BUILD_PROPERTY)).value(filter.getBuilds());
    }

    if (!CollectionUtils.isEmpty(filter.getTestSuites())) {
        result = and(criteriaBuilder, result,
                criteriaBuilder.in(root.get("testSuite").get("id")).value(filter.getTestSuites()));
    }

    if (!CollectionUtils.isEmpty(filter.getGit())) {
        result = and(criteriaBuilder, result,
                criteriaBuilder.or(
                        criteriaBuilder.in(root.get("gitHash")).value(filter.getGit()),
                        criteriaBuilder.in(root.get("gitBranch")).value(filter.getGit())
                ));
    }

    result = and(criteriaBuilder, result, criteriaBuilder.isNotNull(root.get("testSuite")));

    return result;
}
项目:OperatieBRP    文件:LeveringsautorisatieFilterFactory.java   
@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);
}
项目:photoiff    文件:PerfilService.java   
public Pessoa validarUsuario(String log, String pass){
    final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    final CriteriaQuery<Pessoa> cquery = cb.createQuery(Pessoa.class);
    final Root<Pessoa> root = cquery.from(Pessoa.class);
    final List<Predicate> condicoes = new ArrayList<Predicate>();

    condicoes.add(cb.equal(root.get("usuario").get("login"), log));
    condicoes.add(cb.equal(root.get("usuario").get("senha"), pass));

    cquery.select(root).where(condicoes.toArray(new Predicate[]{}));
    Pessoa pessoa = new Pessoa();
    try{
        pessoa = getEntityManager().createQuery(cquery).getSingleResult();
    } catch (Exception e) {
        throw new QueryTimeoutException("Usuário ou senha invalido!");
    }   

    return pessoa;
}
项目:spring-repository-plus    文件:SpecificationImpl.java   
@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()]));
}
项目:bookshelf    文件:BookSpecification.java   
@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]));
}
项目:photoiff    文件:GenericService.java   
public Pessoa validarLoginAdminstrador(String login, String senha){
    final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    final CriteriaQuery<Pessoa> cquery = cb.createQuery(Pessoa.class);
    final Root<Pessoa> root = cquery.from(Pessoa.class);
    final List<Predicate> condicoes = new ArrayList<Predicate>();

    condicoes.add(cb.equal(root.get("usuario").get("matricula"), login));
    condicoes.add(cb.equal(root.get("usuario").get("senha"),senha));

    cquery.select(root).where(condicoes.toArray(new Predicate[]{}));
    Pessoa pessoa = new Pessoa();
    try{
        pessoa = getEntityManager().createQuery(cquery).getSingleResult();
    }catch (Exception e) {
        throw new QueryTimeoutException("Matricula ou Senha Invalidas");
    }

    return pessoa;
}
项目:plumdo-work    文件:LogicalExpression.java   
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query,  
        CriteriaBuilder builder) {  
    List<Predicate> predicates = new ArrayList<Predicate>();  
    for(int i=0;i<this.criterion.length;i++){  
        predicates.add(this.criterion[i].toPredicate(root, query, builder));  
    }  
    switch (operator) {  
    case OR:  
        return builder.or(predicates.toArray(new Predicate[predicates.size()]));  
    default:  
        return null;  
    }  
}
项目:REST-Web-Services    文件:ContributionSpecs.java   
/**
 * 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()]));
}
项目:bootstrap    文件:DynamicSpecification.java   
/**
 * Return a predicate from a rule.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate getPredicate(final Root<U> root, final CriteriaBuilder cb, final BasicRule rule, final CriteriaQuery<?> query) {
    if (rule.getOp() == RuleOperator.CT) {
        return getCustomPredicate(root, cb, rule, query);
    }
    final Expression expression = getOrmPath(root, rule);
    if (expression == null) {
        // Non matched expression, ignore it...
        log.info(String.format("SQL injection attack ? Unable to map request rule for property %s", rule.getField()));
        return null;
    }
    return getPredicate(cb, rule, expression);
}
项目:iotplatform    文件:JpaRelationDao.java   
private Specification<RelationEntity> getEntityFieldsSpec(EntityId from, String relationType,
    RelationTypeGroup typeGroup, ThingType childType) {
  return new Specification<RelationEntity>() {
    @Override
    public Predicate toPredicate(Root<RelationEntity> root, CriteriaQuery<?> criteriaQuery,
        CriteriaBuilder criteriaBuilder) {
      List<Predicate> predicates = new ArrayList<>();
      if (from != null) {
        Predicate fromIdPredicate = criteriaBuilder.equal(root.get("fromId"),
            UUIDConverter.fromTimeUUID(from.getId()));
        predicates.add(fromIdPredicate);
        Predicate fromEntityTypePredicate = criteriaBuilder.equal(root.get("fromType"), from.getEntityType().name());
        predicates.add(fromEntityTypePredicate);
      }
      if (relationType != null) {
        Predicate relationTypePredicate = criteriaBuilder.equal(root.get("relationType"), relationType);
        predicates.add(relationTypePredicate);
      }
      if (typeGroup != null) {
        Predicate typeGroupPredicate = criteriaBuilder.equal(root.get("relationTypeGroup"), typeGroup.name());
        predicates.add(typeGroupPredicate);
      }
      if (childType != null) {
        Predicate childTypePredicate = criteriaBuilder.equal(root.get("toType"), childType.name());
        predicates.add(childTypePredicate);
      }
      return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
    }
  };
}
项目:OperatieBRP    文件:PersoonFilterFactory.java   
@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);
}
项目:sucok-framework    文件:BetweenField.java   
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate buildJpaPredicate(CriteriaBuilder cb, Root root) {
    String field1 = (String) Array.get(value, 0);
    String field2 = (String) Array.get(value, 1);
    Expression<Comparable> path1 = QueryFormHelper.getPath(root, field1);
    Expression<Comparable> path2 = QueryFormHelper.getPath(root, field2);
    Expression<Comparable> parameter = cb.literal((Comparable) value);
    return cb.between(parameter, path1, path2);
}
项目:sucok-framework    文件:GreaterThanOrEqual.java   
@Override
@SuppressWarnings({ "unchecked" })
public Predicate buildJpaPredicate(CriteriaBuilder cb, Root<?> root) {
    Expression<Y> path = QueryFormHelper.getPath(root, field);
    Y num = (Y) value;
    return cb.greaterThanOrEqualTo(path, num);
}
项目:sucok-framework    文件:LessThanOrEqual.java   
@Override
@SuppressWarnings({ "unchecked" })
public Predicate buildJpaPredicate(CriteriaBuilder cb, Root<?> root) {
    Expression<Y> path = QueryFormHelper.getPath(root, field);
    Y num = (Y) value;
    return cb.lessThanOrEqualTo(path, num);
}
项目:sucok-framework    文件:Between.java   
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate buildJpaPredicate(CriteriaBuilder builder, Root root) {
    Expression<Comparable> path = QueryFormHelper.getPath(root, field);
    Comparable value1 = (Comparable) Array.get(value, 0);
    Comparable value2 = (Comparable) Array.get(value, 1);
    return builder.between(path, value1, value2);
}
项目:plumdo-stock    文件:LogicalExpression.java   
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query,  
        CriteriaBuilder builder) {  
    List<Predicate> predicates = new ArrayList<Predicate>();  
    for(int i=0;i<this.criterion.length;i++){  
        predicates.add(this.criterion[i].toPredicate(root, query, builder));  
    }  
    switch (operator) {  
    case OR:  
        return builder.or(predicates.toArray(new Predicate[predicates.size()]));  
    default:  
        return null;  
    }  
}
项目:endpoint-health    文件:EndPointCheckDao.java   
public Collection<EndPointCheck> findByDateRange(final EndPoint endPoint, final Date startDate,
        final Date endDate) {
    final CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    final CriteriaQuery<EndPointCheck> criteriaQuery = criteriaBuilder.createQuery(getEntityClass());
    final Root<EndPointCheck> root = criteriaQuery
            .from(getEntityManager().getMetamodel().entity(getEntityClass()));

    final ParameterExpression<EndPoint> endPointParameter = criteriaBuilder.parameter(EndPoint.class);
    final ParameterExpression<Date> startDateParameter = criteriaBuilder.parameter(Date.class);
    final ParameterExpression<Date> endDateParameter = criteriaBuilder.parameter(Date.class);

    final Predicate endPointIdPredicate = criteriaBuilder
            .equal(root.get("endPoint"), endPointParameter);

    final Path<Date> checkDatePath = root.<Date> get("checkDate");

    final Predicate startDatePredicate = criteriaBuilder
            .greaterThanOrEqualTo(checkDatePath, startDateParameter);

    final Predicate endDatePredicate = criteriaBuilder.lessThanOrEqualTo(
        checkDatePath,
        endDateParameter);

    criteriaQuery.where(criteriaBuilder.and(endPointIdPredicate, startDatePredicate, endDatePredicate));

    criteriaQuery.orderBy(Arrays.asList(criteriaBuilder.asc(checkDatePath)));

    return getEntityManager().createQuery(criteriaQuery)
            .setParameter(endPointParameter, endPoint)
            .setParameter(startDateParameter, startDate, TemporalType.DATE)
            .setParameter(endDateParameter, endDate, TemporalType.DATE)
            .getResultList();
}
项目:careconnect-reference-implementation    文件:CodeSystemDao.java   
@Override
@Transactional
public CodeSystemEntity findBySystem(String system) {

    CriteriaBuilder builder = em.getCriteriaBuilder();

    CodeSystemEntity codeSystemEntity = null;
    CriteriaQuery<CodeSystemEntity> criteria = builder.createQuery(CodeSystemEntity.class);

    Root<CodeSystemEntity> root = criteria.from(CodeSystemEntity.class);
    List<Predicate> predList = new LinkedList<Predicate>();
    log.trace("FlushMode = "+em.getFlushMode());
    log.trace("Entity Manager Properties = "+ em.getProperties().toString());
    Predicate p = builder.equal(root.<String>get("codeSystemUri"),system);
    predList.add(p);
    Predicate[] predArray = new Predicate[predList.size()];
    predList.toArray(predArray);
    if (predList.size()>0)
    {
        log.trace("Found CodeSystem "+system);
        criteria.select(root).where(predArray);

        List<CodeSystemEntity> qryResults = em.createQuery(criteria).getResultList();

        for (CodeSystemEntity cme : qryResults) {
            codeSystemEntity = cme;
            break;
        }
    }
    if (codeSystemEntity == null) {
        log.info("Not found adding CodeSystem = "+system);
        codeSystemEntity = new CodeSystemEntity();
        codeSystemEntity.setCodeSystemUri(system);

        save(codeSystemEntity);

    }
    return codeSystemEntity;
}
项目:photoiff    文件:PerfilService.java   
public List<Pessoa> filtrarPorNome(String filtro){
    final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    final CriteriaQuery<Pessoa> cquery = cb.createQuery(Pessoa.class);
    final Root<Pessoa> root = cquery.from(Pessoa.class);
    final List<Predicate> condicoes = new ArrayList<Predicate>();

    Expression<String> path = root.get("nome");
    condicoes.add(cb.like(path, "%"+filtro+"%"));

    cquery.select(root).where(condicoes.toArray(new Predicate[]{}));
    List<Pessoa> pessoas = getEntityManager().createQuery(cquery).getResultList();

    return pessoas;
}
项目:linq    文件:LindImpl.java   
protected void applyPredicateToCriteria() {
    Predicate predicate = parsePredicate(junction);
    if (predicate != null) {
        if (sq != null) {
            sq.where(predicate);
        } else {
            criteria.where(predicate);
        }
    }
}
项目:cf-mta-deploy-service    文件:DeployTargetDao.java   
private TypedQuery<Dto> createFindByNameQuery(String name) {
    EntityManager em = createEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Dto> query = builder.createQuery(this.classVersion);
    Root<Dto> entity = query.from(this.classVersion);

    Predicate namePredicate = builder.equal(entity.get(DEPLOY_TARGET_NAME), name);
    return em.createQuery(query.select(entity).where(namePredicate));
}
项目:CriteriaBuilder    文件:CriteriaServiceImpl.java   
@Override
public List<?> search(String entityName, String query, int limit, int pageNumber)
{
    List<T> resultsList = new ArrayList<>();

    Class<T> clazz = entityList.get(entityName);

    if(clazz == null) throw new RuntimeException("ENTITY.NOT.FOUND");

    boolean isValid = query == null ? true : validateQuery(query, clazz);  

    if(isValid) {

        CriteriaBuilder criteriaBuilder = entitymanager.getCriteriaBuilder();
        CriteriaQuery<T> cq = criteriaBuilder.createQuery(clazz);

        Root<T> root = cq.from(clazz);          

        if(query!=null) {
            Predicate predicate = populatePredicates(root, query);
            cq.where(predicate);                
        }

           cq.select(root);
           TypedQuery<T> q = entitymanager.createQuery(cq);
           q.setFirstResult((pageNumber-1) * limit);
           q.setMaxResults(limit);
           resultsList = q.getResultList();
           System.out.println(resultsList.size());
    } else {
        throw new RuntimeException("Property defined in the query is not valid, doesn't belong to the entity type:"+entityName);
    }
    return resultsList;
}
项目:CriteriaBuilder    文件:CriteriaServiceImpl.java   
/**
 * input query = field:abcAND(field<bcdOR(field:defANDfield>=efg))
 * return field:abc,field<bcd,field:def,field>=efg,AND,OR,AND
 * @param root 
 * @param query
 * @param predicates 
 * @return 
 * @return
 */
private Predicate populatePredicates(Root<T> root, String query)
{
    if(StringUtils.countOccurrencesOf(query, Conjunctions.SP.toString()) == StringUtils.countOccurrencesOf(query, Conjunctions.EP.toString())) {
        LinkedList<String> postfix = createPostfixExpression(query);
        boolean hasSingleSearchField = postfix.size() == 1;  

        Map<String, Predicate> predicateMap = new LinkedHashMap<>();

        for (int i = 0; i < postfix.size(); i++)
        {
            String attr = postfix.get(i);
            if(Conjunctions.isConjunction(attr)) {

                String rightOperand = postfix.get(i-1);
                String leftOperand = postfix.get(i-2);

                String key = rightOperand + attr + leftOperand;

                Predicate rightPredicate = (predicateMap.containsKey(rightOperand))? predicateMap.get(rightOperand) : buildPredicate(root, new SearchField(rightOperand)); 

                Predicate leftPredicate = (predicateMap.containsKey(leftOperand))? predicateMap.get(leftOperand) : buildPredicate(root, new SearchField(leftOperand));

                postfix.set(i-2, key);
                postfix.remove(i);
                postfix.remove(i-1);

                //reset loop
                i=0;

                List<Predicate> combinedPredicates = new ArrayList<>();
                combinedPredicates.add(leftPredicate);
                combinedPredicates.add(rightPredicate);

                Predicate combinedPredicate = buildPredicateWithOperator(root, Conjunctions.getEnum(attr), combinedPredicates);
                predicateMap.put(key, combinedPredicate);
            }
        }

        if(hasSingleSearchField) {
            SearchField field = new SearchField(postfix.get(0));
            predicateMap.put(postfix.get(0), buildPredicate(root, field));
        }

        return (Predicate) predicateMap.values().toArray()[predicateMap.size()-1];
    } else {
        throw new RuntimeException("MALFORMED.QUERY");
    }
}
项目:OperatieBRP    文件:PredicateBuilderSpecification.java   
@Override
public Predicate toPredicate(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
    final List<Predicate> predicates = new ArrayList<>();

    for (final PredicateBuilder predicateBuilder : predicateBuilders) {
        final Predicate predicate = predicateBuilder.toPredicate(root, query, cb);
        if (predicate != null) {
            predicates.add(predicate);
        }
    }

    return cb.and(predicates.toArray(new Predicate[] {}));
}
项目:CriteriaBuilder    文件:CriteriaServiceImpl.java   
@SuppressWarnings ({ "unchecked", "rawtypes" })
protected Predicate buildPredicate(Path<T> root, SearchField field)
{
    Path<T> tt = (!field.getField().contains(".")) ? root.get(field.getField()) : fetchNestedPath(root, field.getField());
    CriteriaBuilder criteriaBuilder = this.entitymanager.getCriteriaBuilder();

    Class<?> javaType = tt.getJavaType();

    if (!classCompatibleWithOperator(javaType, field.getOperator()))
    {
        throw new RuntimeException("operator incompatible with field");
    }

    Object valueObject = convertStringValueToObject(field.getValue(), javaType);
    switch (field.getOperator())
    {
        case GE:
            return criteriaBuilder.greaterThan((Expression) tt, (Comparable) valueObject);
        case GTE:
            return criteriaBuilder.greaterThanOrEqualTo((Expression) tt, (Comparable) valueObject);
        case LE:
            return criteriaBuilder.lessThan((Expression) tt, (Comparable) valueObject);
        case LTE:
            return criteriaBuilder.lessThanOrEqualTo((Expression) tt, (Comparable) valueObject);
        case NE: 
               return criteriaBuilder.notEqual(tt, valueObject); 
        case EX:
            return criteriaBuilder.like((Expression) tt, "%"+field.getValue()+"%");
        default:
        {
            //EQ
            return criteriaBuilder.equal(tt, valueObject);
        }
    }
}
项目:OperatieBRP    文件:VerConvRepositoryImpl.java   
@Override
public final Lo3Voorkomen zoekLo3VoorkomenVoorActie(final Long actieId) {
    final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    final CriteriaQuery<Lo3Voorkomen> criteria = criteriaBuilder.createQuery(Lo3Voorkomen.class);
    final Root<Lo3Voorkomen> criteriaRoot = criteria.from(Lo3Voorkomen.class);
    criteria.select(criteriaRoot);
    criteria.where(new Predicate[] {criteriaBuilder.equal(criteriaRoot.get("actie").get("id"), actieId) });

    final List<Lo3Voorkomen> result = em.createQuery(criteria).getResultList();
    return result.isEmpty() ? null : result.get(0);
}
项目:bibliometrics    文件:AuthorBuilder.java   
/**
   * gets an author from the database by determining the type of the provided id. if no author is present it builds one from the id.
   * @param id the author identifier
   * @return the author retrieved from the database or build with the identifier
* @throws JDOMException thrown upon parsing the source response
* @throws IOException thrown upon reading profiles from disc
* @throws SAXException thrown when parsing the files from disc
 */
  public PublicationAuthor retrieveAuthor(String id) throws JDOMException, IOException, SAXException {
      typeOfID = determineID(id);
      LOGGER.info("given ID: " + id + " is of type " + typeOfID);
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("publicationAuthors");
      EntityManager em = emf.createEntityManager();
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<PublicationAuthor> q = cb.createQuery(PublicationAuthor.class);
      Root<PublicationAuthor> c = q.from(PublicationAuthor.class);
      List<Predicate> predicates = new ArrayList<>();
      if (typeOfID.equals("surname")) {
          if (id.contains(",")) {
              predicates.add(cb.equal(c.get("surname"),id.substring(0,id.indexOf(","))));
              predicates.add(cb.equal(c.get("firstname"),id.substring(id.indexOf(",")+1)));
              LOGGER.info("retriving surname, firstname from database for " + id);
          } else if (id.contains(" ")) {
              predicates.add(cb.equal(c.get("firstname"),id.substring(0,id.indexOf(" "))));
              predicates.add(cb.equal(c.get("surname"),id.substring(id.indexOf(" ")+1)));
              LOGGER.info("retrieving firstname surname from database for " + id);
          } else {
              predicates.add(cb.equal(c.get("surname"), id));
              LOGGER.info("retrieving surname from database for " + id);
          }
      }
      predicates.add(cb.equal(c.get(typeOfID), id));
      q.select(c).where(cb.equal(c.get(typeOfID), id));
      TypedQuery<PublicationAuthor> query = em.createQuery(q);
      List<PublicationAuthor> authors = query.getResultList();
      em.close();
      if (authors.size() == 1) {
          LOGGER.info("found author in database");
          this.author = authors.get(0);
          return author;
      }
      LOGGER.info("no match in database");
      return buildAuthor(id);
  }
项目:WordnetLoom    文件:SenseSpecification.java   
public static Specification<Sense> filter(SenseCriteriaDTO dto) {

        return (root, query, cb) -> {

            List<Predicate> criteria = new ArrayList<>();

            if (dto.getLemma() != null && !dto.getLemma().isEmpty()) {
                criteria.add(byLemma(dto.getLemma()).toPredicate(root, query, cb));
            }

            if (dto.getVariant() != null) {
                criteria.add(byVarinat(dto.getVariant()).toPredicate(root, query, cb));
            }

            if (dto.getPartOfSpeechId() != null) {
                criteria.add(byPartOfSpeech(dto.getPartOfSpeechId()).toPredicate(root, query, cb));
            }

            if (dto.getDomainId() != null) {
                criteria.add(byDomain(dto.getDomainId()).toPredicate(root, query, cb));
            }

            if (dto.getSynsetId() != null) {
                criteria.add(bySynsetId(dto.getSynsetId()).toPredicate(root, query, cb));
            }

            if (dto.getLexicons() != null && dto.getLexicons().size() > 0) {
                criteria.add(byLexiconIds(dto.getLexicons()).toPredicate(root, query, cb));
            }

            return cb.and(criteria.toArray(new Predicate[criteria.size()]));
        };
    }
项目:WordnetLoom    文件:ExtGraphRepository.java   
public Collection<ExtGraph> findByWordAndPackageNo(String word, int packageno) {

        Long pkg = new Long(packageno);
        CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<ExtGraph> criteriaQuery = criteriaBuilder.createQuery(ExtGraph.class
        );

        Root<ExtGraph> root = criteriaQuery.from(ExtGraph.class);
        Join<ExtGraph, Synset> synset = root.join("synset", JoinType.INNER);
        Join<Synset, Sense> sts = synset.join("sense", JoinType.LEFT);
        List<Predicate> criteriaList = new ArrayList<>();

        Predicate firstCondition = criteriaBuilder.equal(root.get("word"), word);
        criteriaList.add(firstCondition);

        Predicate secondCondition = criteriaBuilder.equal(root.get("packageno"), pkg);
        criteriaList.add(secondCondition);

        Predicate thirdCondition = criteriaBuilder.equal(sts.get("senseIndex"), 0);
        criteriaList.add(thirdCondition);

        criteriaQuery.where(criteriaBuilder.and(criteriaList.toArray(new Predicate[0])));
        final TypedQuery<ExtGraph> query = getEntityManager().createQuery(criteriaQuery);

        return query.getResultList();
    }
项目:flow-platform    文件:AgentDaoImpl.java   
@Override
public List<Agent> list(final String zone, final String orderByField, final AgentStatus... status) {
    if (zone == null) {
        throw new IllegalArgumentException("Zone name is required");
    }

    if (orderByField != null && !orderByFields.contains(orderByField)) {
        throw new IllegalArgumentException(
            "The orderByField only availabe among 'createdDate', 'updateDate' or 'sessionDate'");
    }

    return (List<Agent>) execute(session -> {
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<Agent> criteria = builder.createQuery(Agent.class);

        Root<Agent> root = criteria.from(Agent.class);
        criteria.select(root);

        Predicate whereCriteria = builder.equal(root.get("path").get("zone"), zone);

        if (status != null && status.length > 0) {
            Predicate inStatus = root.get("status").in(status);
            whereCriteria = builder.and(whereCriteria, inStatus);
        }
        criteria.where(whereCriteria);

        // order by created date
        if (orderByField != null) {
            criteria.orderBy(builder.asc(root.get(orderByField)));
        }

        Query<Agent> query = session.createQuery(criteria);
        return query.getResultList();
    });
}
项目:amanda    文件:Criterion.java   
@Override
public Predicate toPredicate(Criterion c, Root<?> r, CriteriaBuilder b) {
    Object o = c.getCompareTo();
    if(o == null)
        return r.get(c.getPropertyName()).in();
    if(o instanceof Collection)
        return r.get(c.getPropertyName()).in((Collection) o);
    throw new IllegalArgumentException(c.getPropertyName());
}