Beispiel #1
11
  public List<Company> retrieveCompanys(String name, String category) {
    EntityManager em = createEntityManager();
    List<Company> company = null;
    try {
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<Company> cq = cb.createQuery(Company.class);
      Root<Company> c = cq.from(Company.class);
      List<Predicate> conditions = new ArrayList<Predicate>();
      if (name != null) {
        Predicate nameCondition = cb.like(c.get(Company_.name), "%" + name + "%");
        conditions.add(nameCondition);
      }
      if (category != null) {
        Path<CompanyCategory> companyCategoryPath = c.get(Company_.category);
        Path<String> companyCategoryNamePath =
            companyCategoryPath.get(CompanyCategory_.categoryName);
        Predicate categoryCondition = cb.like(companyCategoryNamePath, category + "%");
        conditions.add(categoryCondition);
      }
      cq.where(conditions.toArray(new Predicate[0]));
      TypedQuery<Company> query = em.createQuery(cq);
      company = query.getResultList();
    } finally {
      em.close();
    }

    return company;
  }
  /** @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;
  }
Beispiel #3
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;
  }
 /**
  * 废弃
  *
  * @param user
  * @param pageable
  * @return
  */
 public Page<User> getUsersByCondition(User user, Pageable pageable) {
   System.out.println(user);
   CriteriaBuilder cb = em.getCriteriaBuilder();
   CriteriaQuery<User> cq = cb.createQuery(User.class);
   Root<User> root = cq.from(User.class);
   cq.select(root);
   // 使用like的时候可以不用判断是否有该参数传来,因为like %% 就等于没有这个限制条件
   Predicate condition1 =
       cb.like(root.get("username").as(String.class), cb.parameter(String.class, "username"));
   Predicate condition2 =
       cb.like(root.get("userAlias").as(String.class), cb.parameter(String.class, "userAlias"));
   // Predicate
   // condition3=cb.equal(root.get("createTime").as(Date.class),cb.parameter(String.class,
   // "createTime"));
   cq.where(condition1, condition2);
   cb.and(condition1, condition2);
   TypedQuery<User> query = em.createQuery(cq);
   query.setParameter("username", "%" + user.getUsername() + "%");
   query.setParameter("userAlias", "%" + user.getUserAlias() + "%");
   query.setFirstResult(pageable.getOffset());
   query.setMaxResults(pageable.getPageSize());
   List<User> users = query.getResultList();
   Page<User> page = new PageImpl<User>(users, pageable, 10);
   return page;
 }
  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()]);
  }
  private Predicate[] getSearchPredicates(Root<Section> root) {

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

    String name = this.search.getName();
    if (name != null && !"".equals(name)) {
      predicatesList.add(builder.like(root.<String>get("name"), '%' + name + '%'));
    }
    String description = this.search.getDescription();
    if (description != null && !"".equals(description)) {
      predicatesList.add(builder.like(root.<String>get("description"), '%' + description + '%'));
    }
    int numberOfRows = this.search.getNumberOfRows();
    if (numberOfRows != 0) {
      predicatesList.add(builder.equal(root.get("numberOfRows"), numberOfRows));
    }
    int rowCapacity = this.search.getRowCapacity();
    if (rowCapacity != 0) {
      predicatesList.add(builder.equal(root.get("rowCapacity"), rowCapacity));
    }
    Venue venue = this.search.getVenue();
    if (venue != null) {
      predicatesList.add(builder.equal(root.get("venue"), venue));
    }

    return predicatesList.toArray(new Predicate[predicatesList.size()]);
  }
  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;
  }
  @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);
  }
Beispiel #9
0
 @Override
 protected Predicate buildCondition(
     Map.Entry<String, Object> entry, Root<User> root, CriteriaBuilder cb) {
   Predicate predicate = null;
   switch (entry.getKey()) {
     case "username":
       predicate =
           cb.like(
               cb.upper(root.get(entry.getKey())),
               "%" + entry.getValue().toString().toUpperCase() + "%");
       break;
     case "fullname":
       predicate =
           cb.like(
               cb.upper(root.get(entry.getKey())),
               "%" + entry.getValue().toString().toUpperCase() + "%");
       break;
     case "email":
       predicate =
           cb.like(
               cb.upper(root.get(entry.getKey())),
               "%" + entry.getValue().toString().toUpperCase() + "%");
       break;
     case "groups":
       if (entry.getValue() != null) {
         Object[] groups = (Object[]) entry.getValue();
         Predicate[] predicates = new Predicate[groups.length];
         for (int i = 0; i < groups.length; i++) {
           predicates[i] = cb.isMember((User.Group) groups[i], root.get(entry.getKey()));
         }
         predicate = cb.or(predicates);
       }
       break;
     case "description":
       predicate =
           cb.like(
               cb.upper(root.get(entry.getKey())),
               "%" + entry.getValue().toString().toUpperCase() + "%");
       break;
     case "code":
       predicate =
           cb.like(
               cb.upper(root.get(entry.getKey())),
               "%" + entry.getValue().toString().toUpperCase() + "%");
       break;
   }
   return predicate;
 }
Beispiel #10
0
  private Predicate[] getSearchPredicates(Root<Customer> root) {

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

    String firstName = this.search.getFirstName();
    if (firstName != null && !"".equals(firstName)) {
      predicatesList.add(builder.like(root.<String>get("firstName"), '%' + firstName + '%'));
    }
    String lastName = this.search.getLastName();
    if (lastName != null && !"".equals(lastName)) {
      predicatesList.add(builder.like(root.<String>get("lastName"), '%' + lastName + '%'));
    }

    return predicatesList.toArray(new Predicate[predicatesList.size()]);
  }
  @SuppressWarnings("unchecked")
  public static Predicate[] deviceListPredicates(
      CriteriaBuilder cb,
      Root<Device> from,
      Optional<String> name,
      Optional<String> namePattern,
      Optional<String> status,
      Optional<Long> networkId,
      Optional<String> networkName,
      Optional<Long> deviceClassId,
      Optional<String> deviceClassName,
      Optional<String> deviceClassVersion,
      Optional<HivePrincipal> principal) {
    final List<Predicate> predicates = new LinkedList<>();

    name.ifPresent(n -> predicates.add(cb.equal(from.<String>get("name"), n)));
    namePattern.ifPresent(np -> predicates.add(cb.like(from.<String>get("name"), np)));
    status.ifPresent(s -> predicates.add(cb.equal(from.<String>get("status"), s)));

    final Join<Device, Network> networkJoin = (Join) from.fetch("network", JoinType.LEFT);
    networkId.ifPresent(nId -> predicates.add(cb.equal(networkJoin.<Long>get("id"), nId)));
    networkName.ifPresent(
        nName -> predicates.add(cb.equal(networkJoin.<String>get("name"), nName)));

    final Join<Device, DeviceClass> dcJoin = (Join) from.fetch("deviceClass", JoinType.LEFT);
    deviceClassId.ifPresent(dcId -> predicates.add(cb.equal(dcJoin.<Long>get("id"), dcId)));
    deviceClassName.ifPresent(
        dcName -> predicates.add(cb.equal(dcJoin.<String>get("name"), dcName)));
    deviceClassVersion.ifPresent(
        dcVersion -> predicates.add(cb.equal(dcJoin.<String>get("version"), dcVersion)));

    predicates.addAll(deviceSpecificPrincipalPredicates(cb, from, principal));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
  @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());
  }
 @Override
 public List<Employee> findEmployeeByNameStartWith(String reqexp) {
   CriteriaBuilder builder = entityManager.getCriteriaBuilder();
   CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
   Root<Employee> employeeRoot = query.from(Employee.class);
   query.select(employeeRoot).where(builder.like(employeeRoot.<String>get("name"), reqexp + "%"));
   return entityManager.createQuery(query).getResultList();
 }
  @Override
  public Utilisateur findByLoginAndPassword(String login, String password)
      throws DataAccessException {
    try {

      CriteriaBuilder cb = getManager().getCriteriaBuilder();
      CriteriaQuery<Utilisateur> cq = cb.createQuery(Utilisateur.class);
      Root<Utilisateur> uRoot = cq.from(Utilisateur.class);
      cq.where(
          cb.and(
              cb.like(uRoot.get(Utilisateur_.login), login),
              cb.like(uRoot.get(Utilisateur_.password), password)));
      return getManager().createQuery(cq).getSingleResult();
    } catch (NoResultException nre) {
    }
    return null;
  }
 @Override
 public Utilisateur findByLogin(String login) throws DataAccessException {
   CriteriaBuilder cb = getManager().getCriteriaBuilder();
   CriteriaQuery<Utilisateur> cq = cb.createQuery(Utilisateur.class);
   Root<Utilisateur> userRoot = cq.from(Utilisateur.class);
   cq.where(cb.like(userRoot.get(Utilisateur_.login), login));
   return getManager().createQuery(cq).getSingleResult();
 }
 @Override
 public Categorie findByNomenclature(String nomenclature) throws DataAccessException {
   CriteriaBuilder cb = getManager().getCriteriaBuilder();
   CriteriaQuery<Categorie> cq = cb.createQuery(Categorie.class);
   Root<Categorie> cateroot = cq.from(Categorie.class);
   cq.where(cb.like(cateroot.get(Categorie_.nomenclatureSommaire), nomenclature));
   return getManager().createQuery(cq).getSingleResult();
 }
Beispiel #17
0
  /**
   * Applies the criteria found in the {@link SearchCriteriaBean} to the JPA query.
   *
   * @param criteria
   * @param builder
   * @param query
   * @param from
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  protected <T> void applySearchCriteriaToQuery(
      SearchCriteriaBean criteria,
      CriteriaBuilder builder,
      CriteriaQuery<?> query,
      Root<T> from,
      boolean countOnly) {

    List<SearchCriteriaFilterBean> filters = criteria.getFilters();
    if (filters != null && !filters.isEmpty()) {
      List<Predicate> predicates = new ArrayList<>();
      for (SearchCriteriaFilterBean filter : filters) {
        if (filter.getOperator() == SearchCriteriaFilterOperator.eq) {
          Path<Object> path = from.get(filter.getName());
          Class<?> pathc = path.getJavaType();
          if (pathc.isAssignableFrom(String.class)) {
            predicates.add(builder.equal(path, filter.getValue()));
          } else if (pathc.isEnum()) {
            predicates.add(builder.equal(path, Enum.valueOf((Class) pathc, filter.getValue())));
          }
        } else if (filter.getOperator() == SearchCriteriaFilterOperator.bool_eq) {
          predicates.add(
              builder.equal(
                  from.<Boolean>get(filter.getName()), Boolean.valueOf(filter.getValue())));
        } else if (filter.getOperator() == SearchCriteriaFilterOperator.gt) {
          predicates.add(
              builder.greaterThan(from.<Long>get(filter.getName()), new Long(filter.getValue())));
        } else if (filter.getOperator() == SearchCriteriaFilterOperator.gte) {
          predicates.add(
              builder.greaterThanOrEqualTo(
                  from.<Long>get(filter.getName()), new Long(filter.getValue())));
        } else if (filter.getOperator() == SearchCriteriaFilterOperator.lt) {
          predicates.add(
              builder.lessThan(from.<Long>get(filter.getName()), new Long(filter.getValue())));
        } else if (filter.getOperator() == SearchCriteriaFilterOperator.lte) {
          predicates.add(
              builder.lessThanOrEqualTo(
                  from.<Long>get(filter.getName()), new Long(filter.getValue())));
        } else if (filter.getOperator() == SearchCriteriaFilterOperator.neq) {
          predicates.add(builder.notEqual(from.get(filter.getName()), filter.getValue()));
        } else if (filter.getOperator() == SearchCriteriaFilterOperator.like) {
          predicates.add(
              builder.like(
                  builder.upper(from.<String>get(filter.getName())),
                  filter.getValue().toUpperCase().replace('*', '%')));
        }
      }
      query.where(predicates.toArray(new Predicate[predicates.size()]));
    }
    OrderByBean orderBy = criteria.getOrderBy();
    if (orderBy != null && !countOnly) {
      if (orderBy.isAscending()) {
        query.orderBy(builder.asc(from.get(orderBy.getName())));
      } else {
        query.orderBy(builder.desc(from.get(orderBy.getName())));
      }
    }
  }
  @NotNull(message = "{kundeSERV.notFound.criteria}")
  public List<AbstractKunde> findKundenByCriteria(
      String email, String nachname, String vorname, String plz, Date regDate) {
    // SELECT DISTINCT k
    // FROM   AbstractKunde k
    // WHERE  email = ? AND nachname = ? AND k.adresse.plz = ? and seit = ?

    final CriteriaBuilder builder = em.getCriteriaBuilder();
    final CriteriaQuery<AbstractKunde> criteriaQuery = builder.createQuery(AbstractKunde.class);
    final Root<? extends AbstractKunde> k = criteriaQuery.from(AbstractKunde.class);

    Predicate pred = null;
    if (email != null) {
      final Path<String> emailPath = k.get(AbstractKunde_.email);
      final String likeMail = "%" + email + "%";
      pred = builder.like(emailPath, likeMail);
    }
    if (nachname != null) {
      final Path<String> nachnamePath = k.get(AbstractKunde_.nachname);
      final String likeNachname = "%" + nachname + "%";
      final Predicate tmpPred = builder.like(nachnamePath, likeNachname);
      pred = pred == null ? tmpPred : builder.and(pred, tmpPred);
    }
    if (vorname != null) {
      final Path<String> vornamePath = k.get(AbstractKunde_.vorname);
      final String likeVorname = "%" + vorname + "%";
      final Predicate tmpPred = builder.like(vornamePath, likeVorname);
      pred = pred == null ? tmpPred : builder.and(pred, tmpPred);
    }
    if (plz != null) {
      final Path<String> plzPath = k.get(AbstractKunde_.adresse).get(Adresse_.plz);
      final String likePlz = "%" + plz + "%";
      final Predicate tmpPred = builder.like(plzPath, likePlz);
      pred = pred == null ? tmpPred : builder.and(pred, tmpPred);
    }
    if (regDate != null) {
      final Path<Date> regPath = k.get(AbstractKunde_.registrierdatum);
      final Predicate tmpPred = builder.equal(regPath, regDate);
      pred = pred == null ? tmpPred : builder.and(pred, tmpPred);
    }

    criteriaQuery.where(pred).distinct(true);
    return em.createQuery(criteriaQuery).getResultList();
  }
Beispiel #19
0
 public List<Goods> findList(
     ProductCategory productCategory,
     Boolean isMarketable,
     Goods.GenerateMethod generateMethod,
     Date beginDate,
     Date endDate,
     Integer first,
     Integer count) {
   CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
   CriteriaQuery<Goods> criteriaQuery = criteriaBuilder.createQuery(Goods.class);
   Root<Goods> root = criteriaQuery.from(Goods.class);
   criteriaQuery.select(root);
   Predicate restrictions = criteriaBuilder.conjunction();
   if (productCategory != null) {
     Subquery<ProductCategory> subquery = criteriaQuery.subquery(ProductCategory.class);
     Root<ProductCategory> subqueryRoot = subquery.from(ProductCategory.class);
     subquery.select(subqueryRoot);
     subquery.where(
         criteriaBuilder.or(
             criteriaBuilder.equal(subqueryRoot, productCategory),
             criteriaBuilder.like(
                 subqueryRoot.<String>get("treePath"),
                 "%"
                     + ProductCategory.TREE_PATH_SEPARATOR
                     + productCategory.getId()
                     + ProductCategory.TREE_PATH_SEPARATOR
                     + "%")));
     restrictions =
         criteriaBuilder.and(
             restrictions, criteriaBuilder.in(root.get("productCategory")).value(subquery));
   }
   if (isMarketable != null) {
     restrictions =
         criteriaBuilder.and(
             restrictions, criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
   }
   if (generateMethod != null) {
     restrictions =
         criteriaBuilder.and(
             restrictions, criteriaBuilder.equal(root.get("generateMethod"), generateMethod));
   }
   if (beginDate != null) {
     restrictions =
         criteriaBuilder.and(
             restrictions,
             criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
   }
   if (endDate != null) {
     restrictions =
         criteriaBuilder.and(
             restrictions,
             criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate));
   }
   criteriaQuery.where(restrictions);
   return super.findList(criteriaQuery, first, count, null, null);
 }
  private Predicate[] getSearchPredicates(Root<Category> root, Category example) {
    CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
    List<Predicate> predicatesList = new ArrayList<Predicate>();
    String name = example.getName();
    if (name != null && !"".equals(name)) {
      predicatesList.add(builder.like(root.<String>get("name"), '%' + name + '%'));
    }

    return predicatesList.toArray(new Predicate[predicatesList.size()]);
  }
Beispiel #21
0
  private Predicate[] getSearchPredicates(Root<Profile> root) {

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

    String fullName = this.example.getFullName();
    if (fullName != null && !"".equals(fullName)) {
      predicatesList.add(builder.like(root.<String>get("fullName"), '%' + fullName + '%'));
    }
    String email = this.example.getEmail();
    if (email != null && !"".equals(email)) {
      predicatesList.add(builder.like(root.<String>get("email"), '%' + email + '%'));
    }
    String password = this.example.getPassword();
    if (password != null && !"".equals(password)) {
      predicatesList.add(builder.like(root.<String>get("password"), '%' + password + '%'));
    }

    return predicatesList.toArray(new Predicate[predicatesList.size()]);
  }
 public List<Familia> getPorSituacaoELetra(Situacao situacao, String c) {
   CriteriaBuilder cb = em.getCriteriaBuilder();
   CriteriaQuery<Familia> cq = cb.createQuery(Familia.class);
   Root<Familia> rt = cq.from(Familia.class);
   cq.where(
       cb.and(
           cb.equal(rt.get("situacao"), situacao),
           cb.like(cb.upper(rt.get(Familia_.nome)), c.toUpperCase() + "%")));
   cq.orderBy(cb.asc(rt.get(Familia_.nome)));
   return em.createQuery(cq).getResultList();
 }
  /**
   * this method get called by primefaces when loading the data to provide a lazy loading
   *
   * @param first is the index of the first row to display
   * @param pageSize how many rows need to be displayed
   * @param sortField the sort filed if not it's null
   * @param sortOrder always ascending or discending
   * @param filters i don't use them hear cuz it's a bit complex
   * @return the list of the authors feched from the db
   */
  @Override
  public List<Author> load(
      int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
    List<Author> authors;

    // the standart way to make creteria builder,query, form
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Author> cq = cb.createQuery(Author.class);
    Root<Author> form = cq.from(Author.class);

    // make a select operation of authors (form has authors type)
    cq.select(form);

    // if ther is any sorting we add where conditions
    if (sortField != null) {
      if (sortOrder.name().equals("ASCENDING")) {
        cq.orderBy(cb.asc(form.get(sortField)));
      } else {
        cq.orderBy(cb.desc(form.get(sortField)));
      }
    }

    // if the user typed in the global filter we add more where conditions
    if (globalFilter != null) {
      Predicate condition =
          cb.like(form.<String>get("familyName"), "%" + globalFilter.trim() + "%");
      Predicate c2 =
          cb.or(condition, cb.like(form.<String>get("firstName"), "%" + globalFilter.trim() + "%"));
      cq.where(c2);
    }

    // we set the rouw count, primefaces use it to sesplay pages number
    this.setRowCount(JpaUtils.countQueryResults(em, cq).intValue());

    // we make the query and we set the result nbr
    TypedQuery<Author> q = em.createQuery(cq);
    q.setFirstResult(first);
    q.setMaxResults(pageSize);
    authors = q.getResultList();
    return authors;
  }
Beispiel #24
0
  /** @author Romain Wurtz <*****@*****.**> */
  public List<Predicate> createPredicates(
      Root<User> from, CriteriaBuilder criteriaBuilder, Map<String, String> filters) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Iterator<String> it = filters.keySet().iterator(); it.hasNext(); ) {
      String filterProperty = it.next();
      String filterValue = filters.get(filterProperty);

      Expression<String> literal = criteriaBuilder.literal("%" + (String) filterValue + "%");
      predicates.add(criteriaBuilder.like(from.<String>get(filterProperty), literal));
    }
    return predicates;
  }
  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());
     */
  }
Beispiel #26
0
  @Test
  public void jpaCriteriaCodeGen() {
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<Person> criteriaQuery = criteriaBuilder.createQuery(Person.class);
    Root<Person> from = criteriaQuery.from(Person.class);
    Predicate predicate2 = criteriaBuilder.like(from.get(Person_.name), "%");
    criteriaQuery.where(criteriaBuilder.and(predicate2));

    CriteriaQuery<Person> select = criteriaQuery.select(from);
    TypedQuery<Person> typedQuery = em.createQuery(select);
    List<Person> people = typedQuery.getResultList();

    assertThat(people, hasSize(10));
  }
Beispiel #27
0
  public List<Director> getByName(String name) throws Exception {

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery<Director> q = cb.createQuery(Director.class);
    Root<Director> c = q.from(Director.class);
    q.select(c);

    Expression<String> path = c.get("Name");

    q.where(cb.like(path, name));

    return entityManager.createQuery(q).getResultList();
  }
Beispiel #28
0
  private List<GameModel> findPMGs(boolean scenarioOnly) {
    EntityManager em = this.getEntityManager();
    final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    final CriteriaQuery<GameModel> query = criteriaBuilder.createQuery(GameModel.class);

    Root<GameModel> e = query.from(GameModel.class);
    Predicate where;

    if (scenarioOnly) {
      where =
          criteriaBuilder.and(
              criteriaBuilder.equal(e.get("template"), true),
              criteriaBuilder.like(
                  e.get("properties").get("clientScriptUri"), "wegas-pmg/js/wegas-pmg-loader.js%"));
    } else {
      where =
          criteriaBuilder.like(
              e.get("properties").get("clientScriptUri"), "wegas-pmg/js/wegas-pmg-loader.js%");
    }

    query.select(e).where(where);

    return em.createQuery(query).getResultList();
  }
  private Predicate[] getSearchPredicates(Root<ProfiloUsoConsumo> root) {

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

    String nome = this.search.getNome();
    if (nome != null && !"".equals(nome)) {
      predicatesList.add(builder.like(root.<String>get("nome"), '%' + nome + '%'));
    }
    TipologiaValutazione tipo = this.search.getTipo();
    if (tipo != null) {
      predicatesList.add(builder.equal(root.get("tipo"), tipo));
    }
    String descrizione = this.search.getDescrizione();
    if (descrizione != null && !"".equals(descrizione)) {
      predicatesList.add(builder.like(root.<String>get("descrizione"), '%' + descrizione + '%'));
    }
    ComposizioneEdifici composizioneEdificio = this.search.getComposizioneEdificio();
    if (composizioneEdificio != null) {
      predicatesList.add(builder.equal(root.get("composizioneEdificio"), composizioneEdificio));
    }

    return predicatesList.toArray(new Predicate[predicatesList.size()]);
  }
  private static Predicate buildPredicate(
      String name,
      String email,
      String phone,
      String type,
      String region,
      String district,
      String locality,
      String streetToSearch,
      Root<Organization> root,
      CriteriaBuilder cb) {
    Predicate queryPredicate = cb.conjunction();

    if (StringUtils.isNotEmpty(name)) {
      queryPredicate = cb.and(cb.like(root.get("name"), "%" + name + "%"), queryPredicate);
    }

    if (StringUtils.isNotEmpty(email)) {
      queryPredicate = cb.and(cb.like(root.get("email"), "%" + email + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(phone)) {
      queryPredicate = cb.and(cb.like(root.get("phone"), "%" + phone + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(type)) {
      OrganizationType organizationType = OrganizationType.valueOf(type.trim());
      queryPredicate =
          cb.and(cb.isMember(organizationType, root.get("organizationTypes")), queryPredicate);
    }
    if (StringUtils.isNotEmpty(region)) {
      queryPredicate =
          cb.and(cb.like(root.get("address").get("region"), "%" + region + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(district)) {
      queryPredicate =
          cb.and(
              cb.like(root.get("address").get("district"), "%" + district + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(locality)) {
      queryPredicate =
          cb.and(
              cb.like(root.get("address").get("locality"), "%" + locality + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(streetToSearch)) {
      queryPredicate =
          cb.and(
              cb.like(root.get("address").get("street"), "%" + streetToSearch + "%"),
              queryPredicate);
    }

    return queryPredicate;
  }