/** @return Retourne les prédicats utilisés pour effectuer une recherche */
  private List<Predicate> getPredicate(
      CriteriaBuilder cb, Root<ProductEntity> product, String search) {
    List<Predicate> predicates = new ArrayList<>();
    String like = "%" + search.toLowerCase() + "%";

    // Title, description and type
    predicates.add(cb.like(cb.lower(product.get(ProductEntity_.title)), like));
    predicates.add(cb.like(cb.lower(product.get(ProductEntity_.description)), like));
    predicates.add(cb.like(cb.lower(product.get(ProductEntity_.type)), like));

    // Price
    boolean isNumber = true;
    Float price = null;

    try {
      price = Float.valueOf(search);
    } catch (NumberFormatException e) {
      isNumber = false;
    }

    if (isNumber) {
      predicates.add(cb.equal(product.get(ProductEntity_.price), price));
    }

    return predicates;
  }
示例#2
2
  @Override
  public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    Predicate predicate = cb.conjunction();
    List<Expression<Boolean>> expressions = predicate.getExpressions();

    if (isNotBlank(criteria.getFilter())) {
      expressions.add(
          cb.or(
              cb.like(
                  cb.lower(root.<String>get(Role_.roleName)),
                  wildcardsAndLower(criteria.getFilter())),
              cb.like(
                  cb.lower(root.<String>get(Role_.roleDesc)),
                  wildcardsAndLower(criteria.getFilter()))));
    }

    if (isNotBlank(criteria.getRoleName())) {
      expressions.add(
          cb.like(
              cb.lower(root.<String>get(Role_.roleName)),
              wildcardsAndLower(criteria.getRoleName())));
    }
    if (isNotBlank(criteria.getRoleDesc())) {
      expressions.add(
          cb.like(
              cb.lower(root.<String>get(Role_.roleDesc)),
              wildcardsAndLower(criteria.getRoleDesc())));
    }
    if (null != criteria.getIsSys()) {
      expressions.add(cb.equal(root.<Boolean>get(Role_.isSys), criteria.getIsSys()));
    }
    return predicate;
  }
  protected Predicate[] createPredArray(CriteriaBuilder cb, Root root, HttpServletRequest request) {
    List<Predicate> predList = new ArrayList<Predicate>();

    if (request.getParameter("email") != null
        && request.getParameter("email").trim().length() > 0) {
      predList.add(
          cb.like(
              cb.lower(root.get("email")),
              "%" + request.getParameter("email").trim().toLowerCase() + "%"));
    }
    if (request.getParameter("firstName") != null
        && request.getParameter("firstName").trim().length() > 0) {
      predList.add(
          cb.like(
              cb.lower(root.get("firstName")),
              "%" + request.getParameter("firstName").trim().toLowerCase() + "%"));
    }
    if (request.getParameter("lastName") != null
        && request.getParameter("lastName").trim().length() > 0) {
      predList.add(
          cb.like(
              cb.lower(root.get("lastName")),
              "%" + request.getParameter("lastName").trim().toLowerCase() + "%"));
    }
    Predicate[] predArray = new Predicate[predList.size()];
    predList.toArray(predArray);
    return predArray;
  }
  private Predicate[] getSearchPredicates(Root<Author> root) {

    CriteriaBuilder builder = em.getCriteriaBuilder();
    List<Predicate> predicatesList = new ArrayList<>();

    String firstname = example.getFirstname();
    if (firstname != null && !"".equals(firstname)) {
      predicatesList.add(
          builder.like(
              builder.lower(root.<String>get("firstname")), '%' + firstname.toLowerCase() + '%'));
    }
    String surname = example.getSurname();
    if (surname != null && !"".equals(surname)) {
      predicatesList.add(
          builder.like(
              builder.lower(root.<String>get("surname")), '%' + surname.toLowerCase() + '%'));
    }
    String bio = example.getBio();
    if (bio != null && !"".equals(bio)) {
      predicatesList.add(
          builder.like(builder.lower(root.<String>get("bio")), '%' + bio.toLowerCase() + '%'));
    }
    String twitter = example.getTwitter();
    if (twitter != null && !"".equals(twitter)) {
      predicatesList.add(
          builder.like(
              builder.lower(root.<String>get("twitter")), '%' + twitter.toLowerCase() + '%'));
    }

    return predicatesList.toArray(new Predicate[predicatesList.size()]);
  }
示例#5
0
  @Override
  public List<Product> getProductsByConditions(
      String categoryContain, String nameContain, Float priceFrom, Float priceBefore) {
    openConnection();
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> cq = cb.createQuery(Product.class);
    Root<Product> productRoot = cq.from(Product.class);
    List<Predicate> predicates = new ArrayList<Predicate>();

    if (categoryContain != null) {
      if (!categoryContain.equals("")) {
        Expression<String> catName = productRoot.get("cat").get("name");
        Predicate catNameContainPredicate = cb.like(cb.lower(catName), "%" + categoryContain + "%");
        predicates.add(catNameContainPredicate);
      }
    }

    if (nameContain != null) {
      if (!nameContain.equals("")) {
        Expression<String> productName = productRoot.get("name");
        Predicate nameContainPredicate = cb.like(cb.lower(productName), "%" + nameContain + "%");
        predicates.add(nameContainPredicate);
      }
    }

    Expression<Float> price = productRoot.get("price");
    if (priceBefore != null) {
      Predicate pricePredicate = cb.between(price, priceFrom, priceBefore);
      predicates.add(pricePredicate);
    }

    if (priceBefore == null) {
      Predicate pricePredicate = cb.gt(price, priceFrom);
      predicates.add(pricePredicate);
    }

    cq.select(productRoot);

    if (predicates.size() != 0) {
      Predicate[] predicatesArray = new Predicate[predicates.size()];
      cq.where(predicates.toArray(predicatesArray));
    }

    TypedQuery<Product> productTypedQuery = entityManager.createQuery(cq);
    List<Product> productList = productTypedQuery.getResultList();
    closeConnection();

    return DbManagerPersistence.filterProducts(productList, nameContain, categoryContain);
  }
  @Override
  public void doSearch() {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<QuestionType> cquery = builder.createQuery(QuestionType.class);
    Root<QuestionType> rqt = cquery.from(QuestionType.class);

    cquery
        .select(rqt)
        .where(
            builder.like(
                builder.lower(rqt.get(QuestionType_.name)), searchCriteria.getSearchPattern()));

    List<QuestionType> results =
        em.createQuery(cquery)
            .setMaxResults(searchCriteria.getFetchSize())
            .setFirstResult(searchCriteria.getFetchOffset())
            .getResultList();

    nextPageAvailable = results.size() > searchCriteria.getPageSize();
    if (nextPageAvailable) {
      // NOTE create new ArrayList since subList creates unserializable list
      questionTypes = new ArrayList<QuestionType>(results.subList(0, searchCriteria.getPageSize()));
    } else {
      questionTypes = results;
    }
    log.info(
        messageBuilder
            .get()
            .text("Found {0} hotel(s) matching search term [ {1} ] (limit {2})")
            .textParams(
                questionTypes.size(), searchCriteria.getQuery(), searchCriteria.getPageSize())
            .build()
            .getText());
  }
  private void queryHotels(final SearchCriteria criteria) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Hotel> cquery = builder.createQuery(Hotel.class);
    Root<Hotel> hotel = cquery.from(Hotel.class);
    // QUESTION can like create the pattern for us?
    cquery
        .select(hotel)
        .where(
            builder.or(
                builder.like(builder.lower(hotel.get(Hotel_.name)), criteria.getSearchPattern()),
                builder.like(builder.lower(hotel.get(Hotel_.city)), criteria.getSearchPattern()),
                builder.like(builder.lower(hotel.get(Hotel_.zip)), criteria.getSearchPattern()),
                builder.like(
                    builder.lower(hotel.get(Hotel_.address)), criteria.getSearchPattern())));

    List<Hotel> results =
        em.createQuery(cquery)
            .setMaxResults(criteria.getFetchSize())
            .setFirstResult(criteria.getFetchOffset())
            .getResultList();

    nextPageAvailable = results.size() > criteria.getPageSize();
    if (nextPageAvailable) {
      // NOTE create new ArrayList since subList creates unserializable list
      hotels = new ArrayList<Hotel>(results.subList(0, criteria.getPageSize()));
    } else {
      hotels = results;
    }
    log.info(
        messageBuilder
            .get()
            .text("Found {0} hotel(s) matching search term [ {1} ] (limit {2})")
            .textParams(hotels.size(), criteria.getQuery(), criteria.getPageSize())
            .build()
            .getText());
    /*
     * System.out.println(messageBuilder.get().text("Found {0} hotel(s) matching search term [ {1} ] (limit {2})")
     * .textParams(hotels.size(), criteria.getQuery(), criteria.getPageSize()).build().getText());
     */
  }
示例#8
0
  /**
   * Creates a criteria API {@link javax.persistence.criteria.Order} from the given {@link Order}.
   *
   * @param order the order to transform into a JPA {@link javax.persistence.criteria.Order}
   * @param root the {@link Root} the {@link Order} expression is based on
   * @param cb the {@link CriteriaBuilder} to build the {@link javax.persistence.criteria.Order}
   *     with
   * @return
   */
  @SuppressWarnings("unchecked")
  private static javax.persistence.criteria.Order toJpaOrder(
      Order order, Root<?> root, CriteriaBuilder cb) {

    PropertyPath property = PropertyPath.from(order.getProperty(), root.getJavaType());
    Expression<?> expression = toExpressionRecursively(root, property);

    if (order.isIgnoreCase() && String.class.equals(expression.getJavaType())) {
      Expression<String> lower = cb.lower((Expression<String>) expression);
      return order.isAscending() ? cb.asc(lower) : cb.desc(lower);
    } else {
      return order.isAscending() ? cb.asc(expression) : cb.desc(expression);
    }
  }
 @SuppressWarnings({"rawtypes", "unchecked"})
 @Override
 public int obterQtdRegistros(Map<String, String> filters) throws Exception {
   CriteriaBuilder cb = entity.getCriteriaBuilder();
   CriteriaQuery q = cb.createQuery(EEATVolume.class);
   Root<EEATVolume> c = q.from(EEATVolume.class);
   /*
           Join<EEATVolume, RegionalProxy> greg = c.join("regionalProxy");
           Join<EEATVolume, UnidadeNegocioProxy> uneg = c.join("unidadeNegocioProxy");
           Join<EEATVolume, MunicipioProxy> muni = c.join("municipioProxy");
           Join<EEATVolume, LocalidadeProxy> loca = c.join("localidadeProxy");
   */
   Join<EEATVolume, EEAT> eat = c.join("eeat");
   q.select(cb.count(c));
   if (filters != null && !filters.isEmpty()) {
     Predicate[] predicates = new Predicate[filters.size()];
     int i = 0;
     for (Map.Entry<String, String> entry : filters.entrySet()) {
       String key = entry.getKey();
       String val = entry.getValue();
       Expression<String> path;
       try {
         /*
         	                if (key.equals("regionalProxy.nome")) path = greg.get("nome");
         	                else if (key.equals("unidadeNegocioProxy.nome")) path = uneg.get("nome");
         	                else if (key.equals("municipioProxy.nome")) path = muni.get("nome");
         	                else if (key.equals("localidadeProxy.nome")) path = loca.get("nome");
         */
         if (key.equals("eeat.descricao")) path = eat.get("descricao");
         else path = c.get(key);
         if (key.equals("referencia")) {
           SimpleDateFormat formataData = new SimpleDateFormat("MM/yyyy");
           Date dataConsumo = formataData.parse(val);
           predicates[i] = cb.and(cb.equal(path, dataConsumo));
         } else {
           predicates[i] = cb.and(cb.like(cb.lower(path), "%" + val.toLowerCase() + "%"));
         }
       } catch (SecurityException ex) {
         ex.printStackTrace();
       }
       i++;
     }
     q.where(predicates);
   }
   Query query = entity.createQuery(q);
   return ((Long) query.getSingleResult()).intValue();
 }
  private Predicate buildCriteria(
      CriteriaBuilder criteriaBuilder, Root<Product> enityRoot, Map<String, Object> params) {
    String categoryName = (String) params.get("category_name");

    Predicate criteria = criteriaBuilder.conjunction();

    if (categoryName != null && !categoryName.isEmpty()) {
      criteria
          .getExpressions()
          .add(
              criteriaBuilder.like(
                  criteriaBuilder.lower(
                      enityRoot.join("category", JoinType.LEFT).<String>get("name")),
                  "%" + categoryName.toLowerCase() + "%"));
    }
    return criteria;
  }
示例#11
0
  /** This test method demonstrates several date functions */
  @Test
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testStringFunctions() {
    log.info("*** testStringFunctions() ***");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery qdef = cb.createQuery();
    Root<Customer> c = qdef.from(Customer.class);

    // select c from Customer c
    // where c.firstName='CAT'
    qdef.select(c).where(cb.equal(c.get("firstName"), "CAT"));
    int rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows", 0, rows);

    // select c from Customer c
    // where c.firstName=LOWER('CAT')"
    qdef.select(c).where(cb.equal(c.get("firstName"), cb.lower(cb.literal("CAT"))));
    rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows", 1, rows);

    // select UPPER(c.firstName) from Customer c
    // where c.firstName=LOWER('CAT')
    qdef.select(cb.upper(c.<String>get("firstName")))
        .where(cb.equal(c.get("firstName"), cb.lower(cb.literal("CAT"))));
    rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows", 1, rows);

    // TODO: determine why SQL generated without quotes here with H2Dialect
    /*
    Caused by: org.h2.jdbc.JdbcSQLException: Column "C" not found; SQL statement:
    select trim(LEADING c from customer0_.FIRST_NAME) as col_0_0_ from JPAQL_CUSTOMER customer0_
    where customer0_.FIRST_NAME=?
    */

    // select TRIM(LEADING 'c' FROM c.firstName) from Customer c
    // where c.firstName='cat')
    qdef.select(cb.trim(Trimspec.LEADING, 'c', c.<String>get("firstName")))
        .where(cb.equal(c.get("firstName"), "cat"));
    //        List<String> result = executeQuery(qdef);
    //        assertEquals("unexpected number of rows", 1, rows);
    //        assertEquals("unexpected value", "at", result.get(0));

    // select c from Customer c
    // where CONCAT(CONCAT(c.firstName,' '),c.lastName) ='cat inhat')
    qdef.select(c)
        .where(
            cb.equal(
                cb.concat(cb.concat(c.<String>get("firstName"), " "), c.<String>get("lastName")),
                "cat inhat"));
    rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows:" + rows, 1, rows);

    // select c from Customer c
    // where LENGTH(c.firstName) = 3
    qdef.select(c).where(cb.equal(cb.length(c.<String>get("firstName")), 3));
    rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows:" + rows, 1, rows);

    // select c from Customer c " +
    // where LOCATE('cat',c.firstName,2) > 0",
    qdef.select(c).where(cb.greaterThan(cb.locate(c.<String>get("firstName"), "cat", 2), 0));
    rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows:" + rows, 0, rows);

    // select c from Customer c
    // where LOCATE('at',c.firstName,2) > 1
    qdef.select(c).where(cb.greaterThan(cb.locate(c.<String>get("firstName"), "at", 2), 1));
    rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows:" + rows, 1, rows);

    // select SUBSTRING(c.firstName,2,2) from Customer c " +
    // where c.firstName = 'cat'",
    qdef.select(cb.substring(c.<String>get("firstName"), 2, 2))
        .where(cb.equal(c.get("firstName"), "cat"));
    List<String> result = executeQuery(qdef);
    assertEquals("unexpected number of rows", 1, rows);
    assertEquals("unexpected value", "at", result.get(0));

    // select c from Customer c
    // where SUBSTRING(c.firstName,2,2) = 'at'
    qdef.select(c).where(cb.equal(cb.substring(c.<String>get("firstName"), 2, 2), "at"));
    rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows:" + rows, 1, rows);
  }
 @Override
 public List<EEATVolume> obterListaLazy(
     int startingAt, int maxPerPage, Map<String, String> filters) throws Exception {
   CriteriaBuilder cb = entity.getCriteriaBuilder();
   CriteriaQuery<EEATVolume> q = cb.createQuery(EEATVolume.class);
   Root<EEATVolume> c = q.from(EEATVolume.class);
   //        Join<ConsumoETA, RegionalProxy> greg = c.join("regionalProxy");
   //        Join<ConsumoETA, UnidadeNegocioProxy> uneg = c.join("unidadeNegocioProxy");
   //        Join<ConsumoETA, MunicipioProxy> muni = c.join("municipioProxy");
   //        Join<ConsumoETA, LocalidadeProxy> loca = c.join("localidadeProxy");
   Join<EEATVolume, EEAT> eat = c.join("eeat");
   q.select(c);
   if (filters != null && !filters.isEmpty()) {
     Predicate[] predicates = new Predicate[filters.size()];
     int i = 0;
     for (Map.Entry<String, String> entry : filters.entrySet()) {
       String key = entry.getKey();
       String val = entry.getValue();
       Expression<String> path;
       try {
         /*
         	                if (key.equals("regionalProxy.nome")) path = greg.get("nome");
         	                else if (key.equals("unidadeNegocioProxy.nome")) path = uneg.get("nome");
         	                else if (key.equals("municipioProxy.nome")) path = muni.get("nome");
         	                else if (key.equals("localidadeProxy.nome")) path = loca.get("nome");
         */
         if (key.equals("eeat.descricao")) path = eat.get("descricao");
         else path = c.get(key);
         if (key.equals("referencia")) {
           SimpleDateFormat formataData = new SimpleDateFormat("MM/yyyy");
           Date dataConsumo = formataData.parse(val);
           predicates[i] = cb.and(cb.equal(path, dataConsumo));
         } else {
           //                    if
           // (RegionalProxy.class.getDeclaredField(key).getType().equals(String.class)) {
           predicates[i] = cb.and(cb.like(cb.lower(path), "%" + val.toLowerCase() + "%"));
         }
       } catch (SecurityException ex) {
         ex.printStackTrace();
       }
       i++;
     }
     q.where(predicates);
   }
   q.orderBy(cb.desc(c.get("referencia")));
   /*
   if (sortField != null && !sortField.isEmpty()) {
       if (sortOrder.equals(SortOrder.ASCENDING)) {
           q.orderBy(cb.asc(c.get(sortField)));
       } else if (sortOrder.equals(SortOrder.DESCENDING)) {
           q.orderBy(cb.desc(c.get(sortField)));
       }
   }
   */
   TypedQuery<EEATVolume> query = entity.createQuery(q);
   query.setMaxResults(maxPerPage);
   query.setFirstResult(startingAt);
   List<EEATVolume> lista = query.getResultList();
   /*
   for (int i = 0; i < lista.size(); i++) {
   	lista.get(i).setEta(fachadaETA.obterETALazy(lista.get(i).getEta().getCodigo()));
   	lista.get(i).setRegionalProxy(fachadaProxy.getRegional(lista.get(i).getRegionalProxy().getCodigo()));
   	lista.get(i).setUnidadeNegocioProxy(fachadaProxy.getUnidadeNegocio(lista.get(i).getUnidadeNegocioProxy().getCodigo()));
   	lista.get(i).setMunicipioProxy(fachadaProxy.getMunicipio(lista.get(i).getMunicipioProxy().getCodigo()));
   	lista.get(i).setLocalidadeProxy(fachadaProxy.getLocalidade(lista.get(i).getLocalidadeProxy().getCodigo()));
   }
   		*/
   return lista;
 }
  /**
   * Método que obterm uma lista de logradouros com base no exemplo informado
   *
   * @param logradouro Logradouro o exemplo a ser pesquisado
   * @return Set<Logradouro> a lista de logradouros encontrados
   * @throws ServicesException exceção que é disparada quando ocorre qualquer erro no método
   */
  @Override
  public Set<Logradouro> obterListaPeloExemplo(Logradouro logradouro) throws ServicesException {
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Logradouro> criteriaQuery = criteriaBuilder.createQuery(Logradouro.class);
    Root<Logradouro> from = criteriaQuery.from(Logradouro.class);

    Predicate listaRestricoes = criteriaBuilder.conjunction();

    if (logradouro.getCep() != null) {
      Predicate restricaoCep =
          criteriaBuilder.equal(from.get(Logradouro_.cep), logradouro.getCep());
      listaRestricoes = criteriaBuilder.and(restricaoCep);
    }
    if (logradouro.getTipoLogradouro() != null) {
      Predicate restricaoTipoLogradouro =
          criteriaBuilder.equal(
              from.get(Logradouro_.tipoLogradouro), logradouro.getTipoLogradouro());
      listaRestricoes = criteriaBuilder.and(restricaoTipoLogradouro);
    }
    if (StringUtils.isNotBlank(logradouro.getNome())) {
      Predicate restricaoNome =
          criteriaBuilder.like(
              criteriaBuilder.lower(from.get(Logradouro_.nome)),
              "%" + logradouro.getNome().toLowerCase() + "%");
      listaRestricoes = criteriaBuilder.and(restricaoNome);
    }
    if (logradouro.getBairro() != null) {
      if (StringUtils.isNotBlank(logradouro.getBairro().getNome())) {
        Predicate restricaoNome =
            criteriaBuilder.like(
                criteriaBuilder.lower(from.get(Logradouro_.bairro).get(Bairro_.nome)),
                "%" + logradouro.getBairro().getMunicipio().getNome().toLowerCase() + "%");
        listaRestricoes = criteriaBuilder.and(restricaoNome);
      }
      if (logradouro.getBairro().getMunicipio() != null) {
        if (logradouro.getBairro().getMunicipio().getUf() != null) {
          Predicate restricaoUF =
              criteriaBuilder.equal(
                  from.get(Logradouro_.bairro).get(Bairro_.municipio).get(Municipio_.uf),
                  logradouro.getBairro().getMunicipio().getUf());
          listaRestricoes = criteriaBuilder.and(restricaoUF);
        }
        if (StringUtils.isNotBlank(logradouro.getBairro().getMunicipio().getNome())) {
          Predicate restricaoNome =
              criteriaBuilder.like(
                  criteriaBuilder.lower(
                      from.get(Logradouro_.bairro).get(Bairro_.municipio).get(Municipio_.nome)),
                  "%" + logradouro.getBairro().getMunicipio().getNome().toLowerCase() + "%");
          listaRestricoes = criteriaBuilder.and(restricaoNome);
        }
      }
    }

    criteriaQuery.where(listaRestricoes);
    TypedQuery<Logradouro> typedQuery = getEntityManager().createQuery(criteriaQuery);
    Set<Logradouro> lista = new TreeSet<Logradouro>(typedQuery.getResultList());

    // FIXME Solução temporária para evitar o problema de Lazy. Verificar solução melhor
    // posteriormente
    for (Logradouro log : lista) {
      log.getBairro().getNome();
      log.getBairro().getMunicipio().getNome();
      log.getBairro().getMunicipio().getUf();
    }
    return lista;
  }
示例#14
0
 @Override
 public <R> Selection<String> toSelection(
     CriteriaQuery<R> query, CriteriaBuilder builder, Path<? extends P> path) {
   return builder.lower(path.get(getAttribute()));
 }
示例#15
0
  public static Predicate createWhereQuery(CriteriaBuilder cb, Root<?> r, QueryParameters q) {

    Predicate predicate = cb.conjunction();

    for (QueryFilter f : q.getFilters()) {

      Predicate np = null;

      try {

        Path<String> stringField = getCriteraField(f.getField(), r);
        Path<Date> dateField = getCriteraField(f.getField(), r);

        switch (f.getOperation()) {
          case EQ:
            if (f.getDateValue() != null) {
              np = cb.equal(stringField, f.getDateValue());
            } else {
              np = cb.equal(stringField, getValueForPath(stringField, f.getValue()));
            }
            break;
          case EQIC:
            if (f.getDateValue() != null) {
              np = cb.equal(stringField, f.getDateValue());
            } else if (f.getValue() != null) {
              np = cb.equal(cb.lower(stringField), f.getValue().toLowerCase());
            }
            break;
          case NEQ:
            if (f.getDateValue() != null) {
              np = cb.notEqual(stringField, f.getDateValue());
            } else {
              np = cb.notEqual(stringField, getValueForPath(stringField, f.getValue()));
            }
            break;
          case NEQIC:
            if (f.getDateValue() != null) {
              np = cb.notEqual(stringField, f.getDateValue());
            } else if (f.getValue() != null) {
              np = cb.notEqual(cb.lower(stringField), f.getValue().toLowerCase());
            }
            break;
          case LIKE:
            np = cb.like(stringField, f.getValue());
            break;
          case LIKEIC:
            np = cb.like(cb.lower(stringField), f.getValue().toLowerCase());
            break;
          case GT:
            if (f.getDateValue() != null) {
              np = cb.greaterThan(dateField, f.getDateValue());
            } else {
              np = cb.greaterThan(stringField, f.getValue());
            }
            break;
          case GTE:
            if (f.getDateValue() != null) {
              np = cb.greaterThanOrEqualTo(dateField, f.getDateValue());
            } else {
              np = cb.greaterThanOrEqualTo(stringField, f.getValue());
            }
            break;
          case LT:
            if (f.getDateValue() != null) {
              np = cb.lessThan(dateField, f.getDateValue());
            } else {
              np = cb.lessThan(stringField, f.getValue());
            }
            break;
          case LTE:
            if (f.getDateValue() != null) {
              np = cb.lessThanOrEqualTo(dateField, f.getDateValue());
            } else {
              np = cb.lessThanOrEqualTo(stringField, f.getValue());
            }
            break;
          case IN:
            np =
                stringField.in(
                    f.getValues()
                        .stream()
                        .map(s -> getValueForPath(stringField, s))
                        .collect(Collectors.toList()));
            break;
          case INIC:
            np =
                cb.lower(stringField)
                    .in(
                        f.getValues()
                            .stream()
                            .map(String::toLowerCase)
                            .collect(Collectors.toList()));
            break;
          case NIN:
            np =
                cb.not(
                    stringField.in(
                        f.getValues()
                            .stream()
                            .map(s -> getValueForPath(stringField, s))
                            .collect(Collectors.toList())));
            break;
          case NINIC:
            np =
                cb.not(
                    cb.lower(stringField)
                        .in(
                            f.getValues()
                                .stream()
                                .map(String::toLowerCase)
                                .collect(Collectors.toList())));
            break;
          case ISNULL:
            np = cb.isNull(stringField);
            break;
          case ISNOTNULL:
            np = cb.isNotNull(stringField);
            break;
        }
      } catch (IllegalArgumentException e) {

        throw new NoSuchEntityFieldException(
            e.getMessage(), f.getField(), r.getJavaType().getSimpleName());
      }

      predicate = cb.and(predicate, np);
    }

    return predicate;
  }
示例#16
0
  @Override
  public List<Task> findTaskByQuery(TaskQuery query) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Task> q = cb.createQuery(Task.class);

    Root<Task> task = q.from(Task.class);
    q.select(task);

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

    if (query.getTaskId() > 0) {
      predicates.add(cb.equal(task.get("id"), query.getTaskId()));
    }

    if (query.getTitle() != null && !query.getTitle().isEmpty()) {
      predicates.add(cb.like(task.<String>get("title"), "%" + query.getTitle() + "%"));
    }

    if (query.getDescription() != null && !query.getDescription().isEmpty()) {
      predicates.add(cb.like(task.<String>get("description"), '%' + query.getDescription() + '%'));
    }

    Predicate assignPred = null;
    if (query.getAssignee() != null && !query.getAssignee().isEmpty()) {
      assignPred = cb.like(task.<String>get("assignee"), '%' + query.getAssignee() + '%');
    }

    Predicate msPred = null;
    if (query.getMemberships() != null) {
      msPred =
          cb.or(
              task.join("status")
                  .join("project")
                  .join("manager", JoinType.LEFT)
                  .in(query.getMemberships()),
              task.join("status")
                  .join("project")
                  .join("participator", JoinType.LEFT)
                  .in(query.getMemberships()));
    }

    Predicate projectPred = null;
    if (query.getProjectIds() != null) {
      if (query.getProjectIds().size() == 1 && query.getProjectIds().get(0) == 0) {
        projectPred = cb.isNotNull(task.get("status"));
      } else if (query.getProjectIds().isEmpty()) {
        return Collections.emptyList();
      } else {
        projectPred = task.get("status").get("project").get("id").in(query.getProjectIds());
      }
    }

    List<Predicate> tmp = new LinkedList<Predicate>();
    for (String or : query.getOrFields()) {
      if (or.equals(TaskUtil.ASSIGNEE)) {
        tmp.add(assignPred);
      }
      if (or.equals(TaskUtil.MEMBERSHIP)) {
        tmp.add(msPred);
      }
      if (or.equals(TaskUtil.PROJECT)) {
        tmp.add(projectPred);
      }
    }

    if (!tmp.isEmpty()) {
      predicates.add(cb.or(tmp.toArray(new Predicate[tmp.size()])));
    }

    if (!query.getOrFields().contains(TaskUtil.ASSIGNEE) && assignPred != null) {
      predicates.add(assignPred);
    }
    if (!query.getOrFields().contains(TaskUtil.MEMBERSHIP) && msPred != null) {
      predicates.add(msPred);
    }
    if (!query.getOrFields().contains(TaskUtil.PROJECT) && projectPred != null) {
      predicates.add(projectPred);
    }

    if (query.getKeyword() != null && !query.getKeyword().isEmpty()) {
      List<Predicate> keyConditions = new LinkedList<Predicate>();
      for (String k : query.getKeyword().split(" ")) {
        if (!(k = k.trim()).isEmpty()) {
          k = "%" + k.toLowerCase() + "%";
          keyConditions.add(
              cb.or(
                  cb.like(cb.lower(task.<String>get("title")), k),
                  cb.like(cb.lower(task.<String>get("description")), k),
                  cb.like(cb.lower(task.<String>get("assignee")), k)));
        }
      }
      predicates.add(cb.or(keyConditions.toArray(new Predicate[keyConditions.size()])));
    }

    if (query.getCompleted() != null) {
      if (query.getCompleted()) {
        predicates.add(cb.equal(task.get("completed"), query.getCompleted()));
      } else {
        predicates.add(cb.notEqual(task.get("completed"), !query.getCompleted()));
      }
    }

    if (query.getCalendarIntegrated() != null) {
      if (query.getCalendarIntegrated()) {
        predicates.add(cb.equal(task.get("calendarIntegrated"), query.getCalendarIntegrated()));
      } else {
        predicates.add(cb.notEqual(task.get("calendarIntegrated"), !query.getCalendarIntegrated()));
      }
    }

    if (query.getStartDate() != null) {
      predicates.add(cb.greaterThanOrEqualTo(task.<Date>get("endDate"), query.getStartDate()));
    }
    if (query.getEndDate() != null) {
      predicates.add(cb.lessThanOrEqualTo(task.<Date>get("startDate"), query.getEndDate()));
    }

    if (predicates.size() > 0) {
      Iterator<Predicate> it = predicates.iterator();
      Predicate p = it.next();
      while (it.hasNext()) {
        p = cb.and(p, it.next());
      }
      q.where(p);
    }

    if (query.getOrderBy() != null && !query.getOrderBy().isEmpty()) {
      List<OrderBy> orderBies = query.getOrderBy();
      Order[] orders = new Order[orderBies.size()];
      for (int i = 0; i < orders.length; i++) {
        OrderBy orderBy = orderBies.get(i);
        Path p = task.get(orderBy.getFieldName());
        orders[i] = orderBy.isAscending() ? cb.asc(p) : cb.desc(p);
      }
      q.orderBy(orders);
    }

    return em.createQuery(q).getResultList();
  }