示例#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;
  }
  public static CriteriaQuery<Organization> buildSearchQuery(
      String name,
      String email,
      String phone,
      String type,
      String region,
      String district,
      String locality,
      String streetToSearch,
      String sortCriteria,
      String sortOrder,
      EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Organization> criteriaQuery = cb.createQuery(Organization.class);
    Root<Organization> root = criteriaQuery.from(Organization.class);

    Predicate predicate =
        ArchivalOrganizationsQueryConstructorAdmin.buildPredicate(
            name, email, type, phone, region, district, locality, streetToSearch, root, cb);
    if ((sortCriteria != null) && (sortOrder != null)) {
      criteriaQuery.orderBy(
          SortCriteriaOrganization.valueOf(sortCriteria.toUpperCase())
              .getSortOrder(root, cb, sortOrder));
    } else {
      criteriaQuery.orderBy(cb.desc(root.get("id")));
    }
    criteriaQuery.select(root);
    criteriaQuery.where(predicate);
    return criteriaQuery;
  }
  @Transactional(propagation = Propagation.NOT_SUPPORTED)
  public List<AccessKey> list(
      Long userId,
      String label,
      String labelPattern,
      Integer type,
      String sortField,
      Boolean sortOrderAsc,
      Integer take,
      Integer skip) {
    CriteriaBuilder cb = genericDAO.criteriaBuilder();
    CriteriaQuery<AccessKey> cq = cb.createQuery(AccessKey.class);
    Root<AccessKey> from = cq.from(AccessKey.class);

    Predicate[] predicates =
        CriteriaHelper.accessKeyListPredicates(
            cb, from, userId, ofNullable(label), ofNullable(labelPattern), ofNullable(type));
    cq.where(predicates);
    CriteriaHelper.order(cb, cq, from, ofNullable(sortField), Boolean.TRUE.equals(sortOrderAsc));

    TypedQuery<AccessKey> query = genericDAO.createQuery(cq);
    ofNullable(skip).ifPresent(query::setFirstResult);
    ofNullable(take).ifPresent(query::setMaxResults);
    genericDAO.cacheQuery(query, of(CacheConfig.bypass()));
    return query.getResultList();
  }
 protected static Predicate getPredicate(
     final Class clazz,
     final Restriction searchTerms,
     Root<Persistable> root,
     CriteriaBuilder cb) {
   LinkedList<Predicate> predicates = new LinkedList<Predicate>();
   Predicate predicate;
   // process child restrictions
   if (!CollectionUtils.isEmpty(searchTerms.getRestrictions())) {
     for (Restriction restriction : searchTerms.getRestrictions()) {
       predicates.add(getPredicate(clazz, restriction, root, cb));
     }
   }
   // process main restriction
   if (StringUtils.isNotBlank(searchTerms.getField())) {
     String propertyName = searchTerms.getField();
     addPredicate(
         clazz,
         root,
         cb,
         predicates,
         searchTerms.getValues().toArray(new String[searchTerms.getValues().size()]),
         propertyName);
   }
   if (searchTerms.getJunction().equals(Restriction.Junction.OR)) {
     predicate = cb.or(predicates.toArray(new Predicate[predicates.size()]));
   } else {
     predicate = cb.and(predicates.toArray(new Predicate[predicates.size()]));
   }
   return predicate;
 }
示例#5
0
  @Override
  public <T extends StoredObject> List<T> getStoredObjects(final Class<T> tClass) {
    List<T> list = Collections.emptyList();

    emLock.lock();

    try {
      final Future<List<T>> future =
          executorService.submit(
              () -> {
                final CriteriaBuilder cb = em.getCriteriaBuilder();
                final CriteriaQuery<T> cq = cb.createQuery(tClass);
                final Root<T> root = cq.from(tClass);
                cq.select(root);

                final TypedQuery<T> q = em.createQuery(cq);

                return new ArrayList<>(q.getResultList());
              });

      list = future.get();
    } catch (InterruptedException | ExecutionException e) {
      logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } finally {
      emLock.unlock();
    }

    return stripMarkedForRemoval(list);
  }
示例#6
0
  /** This test provides a demonstration of testing membership in a collection. */
  @Test
  public void testMemberOf() {
    log.info("*** testMemberOf() ***");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Clerk> qdef = cb.createQuery(Clerk.class);

    // select c from Clerk c where c.firstName = 'Manny'
    Root<Clerk> c = qdef.from(Clerk.class);
    qdef.select(c).where(cb.equal(c.get("firstName"), "Manny"));
    Clerk clerk = em.createQuery(qdef).getSingleResult();

    // find all sales that involve this clerk
    CriteriaQuery<Sale> qdef2 = cb.createQuery(Sale.class);
    // select s from Sale s
    // where :clerk MEMBER OF s.clerks",
    Root<Sale> s = qdef2.from(Sale.class);
    qdef2.select(s).where(cb.isMember(clerk, s.<List<Clerk>>get("clerks")));
    List<Sale> sales = em.createQuery(qdef2).getResultList();

    for (Sale result : sales) {
      log.info("found=" + result);
    }
    assertEquals("unexpected number of rows", 2, sales.size());
  }
示例#7
0
  /** This test demonstrates the use of DISTINCT to limit the results to only unique values */
  @Test
  public void testDISTINCT() {
    log.info("*** testDISTINCT() ***");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    {
      CriteriaQuery<String> qdef = cb.createQuery(String.class);

      // select DISTINCT c.lastName from Customer c
      Root<Customer> c = qdef.from(Customer.class);
      qdef.select(c.<String>get("lastName")).distinct(true);

      int rows = executeQuery(qdef).size();
      assertEquals("unexpected number of rows", 3, rows);
    }

    {
      CriteriaQuery<String> qdef = cb.createQuery(String.class);

      // select DISTINCT c.firstName from Customer c
      Root<Customer> c = qdef.from(Customer.class);
      qdef.select(c.<String>get("firstName")).distinct(true);

      int rows = executeQuery(qdef).size();
      assertEquals("unexpected number of rows for DISTINCT", 2, rows);
    }
  }
示例#8
0
  @Test
  @Transactional
  public void testCopy() {
    EntityManager em = bookDao.getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Book> criteria = cb.createQuery(Book.class);

    // Fetch join
    Root<Book> root = criteria.from(Book.class);
    Path<String> path = root.join("author").<String>get("name");
    root.fetch("author");
    criteria.select(root);

    // SubQuery
    Subquery<String> sq = criteria.subquery(String.class);
    Root<Author> author = sq.from(Author.class);
    sq.select(author.<String>get("name"));
    sq.where(cb.equal(author.<String>get("name"), "Rod"));

    criteria.where(cb.in(path).value(sq));

    CriteriaQuery<Book> copy = cb.createQuery(Book.class);
    JpaUtils.copyCriteria(criteria, copy);

    List<Book> copyBooks = em.createQuery(copy).getResultList();
    List<Book> books = em.createQuery(criteria).getResultList();
    assertEquals(books, copyBooks);
  }
示例#9
0
 /** Load business rules */
 private void loadList() {
   CriteriaBuilder cb = em.getCriteriaBuilder();
   CriteriaQuery<BusinessRule> c = cb.createQuery(BusinessRule.class);
   Root<BusinessRule> obj = c.from(BusinessRule.class);
   c.select(obj).where(cb.equal(obj.get("project"), this.project)).orderBy(cb.asc(obj.get("id")));
   this.businessRules = em.createQuery(c).getResultList();
 }
  @Override
  public ReferenceNumberType getByCode(String code) {
    ReferenceNumberType org = null;

    try {
      CriteriaBuilder builder = em.getCriteriaBuilder();
      CriteriaQuery<ReferenceNumberType> query = builder.createQuery(ReferenceNumberType.class);
      Root<ReferenceNumberType> rootEntity = query.from(ReferenceNumberType.class);
      ParameterExpression<String> p = builder.parameter(String.class);
      query.select(rootEntity).where(builder.equal(rootEntity.get("code"), p));

      TypedQuery<ReferenceNumberType> typedQuery = em.createQuery(query);
      typedQuery.setParameter(p, code);

      org = typedQuery.getSingleResult();
      // TypedQuery<ReferenceNumberType> q = em.createQuery("select o from
      // com.conx.logistics.mdm.domain.referencenumber.ReferenceNumberType o WHERE o.code =
      // :code",ReferenceNumberType.class);
      // q.setParameter("code", code);

      // org = q.getSingleResult();
    } catch (NoResultException e) {
    } catch (Exception e) {
      e.printStackTrace();
    } catch (Error e) {
      StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      String stacktrace = sw.toString();
      logger.error(stacktrace);
    }

    return org;
  }
示例#11
0
 /** load authUsers */
 private void loadList() {
   CriteriaBuilder cb = em.getCriteriaBuilder();
   CriteriaQuery<AuthUser> c = cb.createQuery(AuthUser.class);
   Root<AuthUser> obj = c.from(AuthUser.class);
   c.select(obj).orderBy(cb.asc(obj.get("name")));
   this.authUsers = em.createQuery(c).getResultList();
 }
示例#12
0
 public List<Service> findByContract(Contract contract) {
   CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
   CriteriaQuery<Service> cq = cb.createQuery(Service.class);
   Root<Service> rt = cq.from(Service.class);
   cq.select(rt).where(cb.equal(rt.get(Service_.contract), contract));
   return getEntityManager().createQuery(cq).getResultList();
 }
 public List<Gestion> findAll() {
   CriteriaBuilder cb = em.getCriteriaBuilder();
   CriteriaQuery<Gestion> criteria = cb.createQuery(Gestion.class);
   Root<Gestion> gestion = criteria.from(Gestion.class);
   criteria.select(gestion);
   return em.createQuery(criteria).getResultList();
 }
示例#14
0
  @Override
  public List<TrashObject> getTrashObjects() {
    List<TrashObject> trashObjectList = Collections.emptyList();

    emLock.lock();

    try {
      final Future<List<TrashObject>> future =
          executorService.submit(
              () -> {
                final CriteriaBuilder cb = em.getCriteriaBuilder();
                final CriteriaQuery<TrashObject> cq = cb.createQuery(TrashObject.class);
                final Root<TrashObject> root = cq.from(TrashObject.class);
                cq.select(root);

                final TypedQuery<TrashObject> q = em.createQuery(cq);

                return new ArrayList<>(q.getResultList());
              });

      trashObjectList = future.get();
    } catch (final InterruptedException | ExecutionException e) {
      logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } finally {
      emLock.unlock();
    }

    return trashObjectList;
  }
示例#15
0
文件: SaleDao_.java 项目: BID4WIN/B4W
  /**
   * TODO A COMMENTER
   *
   * @param stepArray TODO A COMMENTER
   * @return TODO A COMMENTER
   * @throws PersistenceException TODO A COMMENTER
   */
  protected CriteriaQuery<SALE> getCriteriaForStep(Step... stepArray) throws PersistenceException {
    CriteriaBuilder builder = this.getCriteriaBuilder();

    CriteriaQuery<SALE> criteria = this.createCriteria();
    Root<SALE> sale_ = criteria.from(this.getEntityClass());
    if (stepArray.length != 0) {
      Path<SaleStep> saleStep_ = this.getSaleStepPath(sale_);
      Bid4WinSet<Step> stepSet = new Bid4WinSet<Step>();
      for (Step step : stepArray) {
        stepSet.add(step);
        stepSet.addAll(step.getRecursiveSubtypeSet());
      }
      Predicate[] predicates = new Predicate[stepSet.size()];
      int i = 0;
      try {
        for (Step step : stepSet) {
          predicates[i++] = builder.equal(saleStep_, new SaleStep(step));
        }
      } catch (UserException ex) {
        throw new PersistenceException(ex);
      }
      Predicate condition = builder.or(predicates);
      criteria.where(condition);
    }
    return criteria;
  }
 protected Predicate[] getPredicates(CriteriaBuilder cb, Root<OutgoingDocument> root) {
   List<Predicate> predicates = new ArrayList<>();
   predicates.add(
       cb.notEqual(root.get(OutgoingDocument_.documentCondition), DocumentCondition.DELETED));
   predicates.add(cb.equal(root.get(OutgoingDocument_.registratorEmployee), getCurrentEmployee()));
   return predicates.toArray(new Predicate[predicates.size()]);
 }
  public List<MyClass138> findByCriteria(MyClass138Criteria myClass138Criteria) {
    javax.persistence.criteria.CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery<MyClass138> c = cb.createQuery(MyClass138.class);
    javax.persistence.criteria.Root<MyClass138> emp = c.from(MyClass138.class);
    c.select(emp);

    List<javax.persistence.criteria.Predicate> criteria =
        new java.util.ArrayList<javax.persistence.criteria.Predicate>();

    if (myClass138Criteria.getId() != null) {
      javax.persistence.criteria.Expression<Long> p = emp.get("id");
      javax.persistence.criteria.Expression<Long> val = cb.parameter(Long.class, "id");
      criteria.add(cb.equal(p, val));
    }

    if (criteria.size() == 1) {
      c.where(criteria.get(0));
    } else {
      c.where(cb.and(criteria.toArray(new javax.persistence.criteria.Predicate[0])));
    }
    javax.persistence.TypedQuery<MyClass138> q = this.entityManager.createQuery(c);

    if (myClass138Criteria.getId() != null) {
      q.setParameter("id", myClass138Criteria.getId());
    }

    return new java.util.ArrayList<MyClass138>(q.getResultList());
  }
  public static <E> Predicate byRanges(
      Root<E> root,
      CriteriaQuery<?> query,
      CriteriaBuilder builder,
      final List<Range<?, ?>> ranges,
      final Class<E> type) {

    List<Predicate> predicates = newArrayList();
    for (Range<?, ?> r : ranges) {
      @SuppressWarnings("unchecked")
      Range<E, ?> range = (Range<E, ?>) r;
      if (range.isSet()) {
        Predicate rangePredicate = buildRangePredicate(range, root, builder);

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

        // no range at all, let's take the opportunity to keep only null...
        if (TRUE == range.getIncludeNull()) {
          predicates.add(builder.isNull(root.get(range.getField())));
        } else if (FALSE == range.getIncludeNull()) {
          predicates.add(builder.isNotNull(root.get(range.getField())));
        }
      }
    }

    return JpaUtil.andPredicate(builder, predicates);
  }
示例#19
0
  /** This test provides an example collection path using an LEFT OUTER JOIN */
  @Test
  public void testOuterJoin() {
    log.info("*** testOuterJoin() ***");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> qdef = cb.createQuery(Object[].class);

    // select c.id, c.firstName, sale.amount
    // from Clerk c
    // LEFT JOIN c.sales sale
    Root<Clerk> c = qdef.from(Clerk.class);
    Join<Clerk, Sale> sale = c.join("sales", JoinType.LEFT);
    qdef.select(cb.array(c.get("id"), c.get("firstName"), sale.get("amount")));

    TypedQuery<Object[]> query = em.createQuery(qdef);
    List<Object[]> results = query.getResultList();
    assertTrue("no results", results.size() > 0);
    for (Object[] result : results) {
      assertEquals("unexpected result length", 3, result.length);
      Long id = (Long) result[0];
      String name = (String) result[1];
      BigDecimal amount = (BigDecimal) result[2];
      log.info("clerk.id=" + id + ", clerk.firstName=" + name + ", amount=" + amount);
    }
  }
示例#20
0
  /**
   * Count the objects in the database
   *
   * @return Number of objects
   */
  public int count() {
    CriteriaBuilder b = getBuilder();
    CriteriaQuery<Long> criteria = b.createQuery(Long.class);
    criteria.select(b.count(criteria.from(domainClass)));

    return em.createQuery(criteria).getSingleResult().intValue();
  }
示例#21
0
  /** This test provides an example of testing whether the collection is empty */
  @Test
  public void testIsEmpty() {
    log.info("*** testIsEmpty() ***");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    {
      CriteriaQuery<Clerk> qdef = cb.createQuery(Clerk.class);

      // select c from Clerk c
      // where c.sales IS EMPTY
      Root<Clerk> c = qdef.from(Clerk.class);
      qdef.select(c).where(cb.isEmpty(c.<List<Sale>>get("sales")));

      int rows = executeQuery(qdef).size();
      assertEquals("unexpected number of rows", 1, rows);
    }

    {
      CriteriaQuery<Clerk> qdef = cb.createQuery(Clerk.class);

      // select c from Clerk c
      // where c.sales IS NOT EMPTY
      Root<Clerk> c = qdef.from(Clerk.class);
      qdef.select(c).where(cb.isNotEmpty(c.<List<Sale>>get("sales")));

      int rows = executeQuery(qdef).size();
      assertEquals("unexpected number of rows", 2, rows);
    }
  }
示例#22
0
  public List<Artikel> findArtikelByIds(List<Long> ids) {
    if (ids == null || ids.isEmpty()) {
      return Collections.emptyList();
    }

    /*
     * SELECT a FROM Artikel a WHERE a.id = ? OR a.id = ? OR ...
     */
    final CriteriaBuilder builder = em.getCriteriaBuilder();
    final CriteriaQuery<Artikel> criteriaQuery = builder.createQuery(Artikel.class);
    final Root<Artikel> a = criteriaQuery.from(Artikel.class);

    final Path<Long> idPath = a.get("id");
    // final Path<String> idPath = a.get(Artikel_.id); // Metamodel-Klassen funktionieren nicht mit
    // Eclipse

    Predicate pred = null;
    if (ids.size() == 1) {
      // Genau 1 id: kein OR notwendig
      pred = builder.equal(idPath, ids.get(0));
    } else {
      // Mind. 2x id, durch OR verknuepft
      final Predicate[] equals = new Predicate[ids.size()];
      int i = 0;
      for (Long id : ids) {
        equals[i++] = builder.equal(idPath, id);
      }

      pred = builder.or(equals);
    }
    criteriaQuery.where(pred);

    return em.createQuery(criteriaQuery).getResultList();
  }
示例#23
0
  /** This test provides a demonstration of using an explicit subquery */
  @Test
  public void testSubqueries() {
    log.info("*** testSubqueries() ***");

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

    // select c from Customer c
    // where c.id IN
    //    (select s.buyerId from Sale s
    //     where s.amount > 100)

    // form subquery
    Subquery<Long> sqdef = qdef.subquery(Long.class);
    Root<Sale> s = sqdef.from(Sale.class);
    sqdef
        .select(s.<Long>get("buyerId"))
        .where(cb.greaterThan(s.<BigDecimal>get("amount"), new BigDecimal(100)));

    // form outer query
    Root<Customer> c = qdef.from(Customer.class);
    qdef.select(c).where(cb.in(c.get("id")).value(sqdef));

    int rows = executeQuery(qdef).size();
    assertEquals("unexpected number of rows", 1, rows);
  }
  public void testMetamodelOnClauseOverCollection() {
    EntityManager em = createEntityManager();
    Query query =
        em.createQuery("Select e from Employee e join e.phoneNumbers p on p.areaCode = '613'");
    List baseResult = query.getResultList();

    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
    Metamodel metamodel = em.getMetamodel();
    EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class);
    EntityType<PhoneNumber> entityPhone_ = metamodel.entity(PhoneNumber.class);

    Root<Employee> root = cq.from(entityEmp_);
    Join phoneNumber = root.join(entityEmp_.getCollection("phoneNumbers"));
    phoneNumber.on(qb.equal(phoneNumber.get(entityPhone_.getSingularAttribute("areaCode")), "613"));
    List testResult = em.createQuery(cq).getResultList();

    clearCache();
    closeEntityManager(em);

    if (baseResult.size() != testResult.size()) {
      fail(
          "Criteria query using ON clause did not match JPQL results; "
              + baseResult.size()
              + " were expected, while criteria query returned "
              + testResult.size());
    }
  }
示例#25
0
  @Override
  public final List<T> findListByProperty(
      final Object[] values, final SingularAttribute<T, ? extends Object>... properties) {
    final CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(persistentClass);
    final Root<T> root = criteriaQuery.from(persistentClass);
    criteriaQuery.select(root);

    final Object value = values[0];
    final SingularAttribute<T, ? extends Object> property = properties[0];
    Predicate condition;

    condition =
        QueryHelper.equalsIgnoreCaseIfStringPredicate(criteriaBuilder, root, value, property);

    if (values.length > 1) {
      for (int i = 1; i < properties.length; i++) {
        final SingularAttribute<T, ? extends Object> property2 = properties[i];
        final Object value2 = values[i];
        final Predicate condition2 =
            QueryHelper.equalsIgnoreCaseIfStringPredicate(criteriaBuilder, root, value2, property2);

        condition = criteriaBuilder.and(condition, condition2);
      }
    }

    criteriaQuery.where(condition);

    final TypedQuery<T> typedQuery = getEntityManager().createQuery(criteriaQuery);
    addCacheHints(typedQuery, "findListByProperty");

    return typedQuery.getResultList();
  }
  public void testMetamodelOnClauseWithLeftJoin() {
    EntityManager em = createEntityManager();
    Query query =
        em.createQuery(
            "Select e from Employee e left join e.address a on a.city = 'Ottawa' "
                + "where a.postalCode is not null");
    List baseResult = query.getResultList();

    Metamodel metamodel = em.getMetamodel();
    EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class);
    EntityType<Address> entityAddr_ = metamodel.entity(Address.class);

    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
    Root<Employee> root = cq.from(entityEmp_);
    Join address = root.join(entityEmp_.getSingularAttribute("address"), JoinType.LEFT);
    address.on(qb.equal(address.get(entityAddr_.getSingularAttribute("city")), "Ottawa"));
    cq.where(qb.isNotNull(address.get(entityAddr_.getSingularAttribute("postalCode"))));
    List testResult = em.createQuery(cq).getResultList();

    clearCache();
    closeEntityManager(em);

    if (baseResult.size() != testResult.size()) {
      fail(
          "Criteria query using ON clause with a left join did not match JPQL results; "
              + baseResult.size()
              + " were expected, while criteria query returned "
              + testResult.size());
    }
  }
 protected static Predicate getPredicate(
     final Class clazz,
     final Map<String, String[]> searchTerms,
     Root<Persistable> root,
     CriteriaBuilder cb) {
   LinkedList<Predicate> predicates = new LinkedList<Predicate>();
   Predicate predicate;
   if (!CollectionUtils.isEmpty(searchTerms)) {
     Set<String> propertyNames = searchTerms.keySet();
     // put aside nested AND/OR param groups
     NestedJunctions junctions = new NestedJunctions();
     for (String propertyName : propertyNames) {
       String[] values = searchTerms.get(propertyName);
       if (!junctions.addIfNestedJunction(propertyName, values)) {
         addPredicate(clazz, root, cb, predicates, values, propertyName);
       }
     }
     // add nested AND/OR param groups
     Map<String, Map<String, String[]>> andJunctions = junctions.getAndJunctions();
     addJunctionedParams(clazz, root, cb, predicates, andJunctions, AND);
     Map<String, Map<String, String[]>> orJunctions = junctions.getOrJunctions();
     addJunctionedParams(clazz, root, cb, predicates, orJunctions, OR);
   }
   if (searchTerms.containsKey(SEARCH_MODE)
       && searchTerms.get(SEARCH_MODE)[0].equalsIgnoreCase(OR)) {
     predicate = cb.or(predicates.toArray(new Predicate[predicates.size()]));
   } else {
     predicate = cb.and(predicates.toArray(new Predicate[predicates.size()]));
   }
   return predicate;
 }
示例#28
0
 public List<Equipment> findAllOrderedByProductionDate() {
   CriteriaBuilder cb = em.getCriteriaBuilder();
   CriteriaQuery<Equipment> criteria = cb.createQuery(Equipment.class);
   Root<Equipment> equipment = criteria.from(Equipment.class);
   criteria.select(equipment).orderBy(cb.desc(equipment.get("productionDate")));
   return em.createQuery(criteria).getResultList();
 }
示例#29
0
 /**
  * Service method to return all StockCategory from database
  *
  * @return
  */
 public List<StockCategory> findAllStockCategories() {
   CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
   CriteriaQuery<StockCategory> criteria = criteriaBuilder.createQuery(StockCategory.class);
   Root<StockCategory> stockCategory = criteria.from(StockCategory.class);
   criteria.select(stockCategory);
   return entityManager.createQuery(criteria).getResultList();
 }
  public <E> Predicate byEntitySelectors(
      Root<E> root, CriteriaBuilder builder, SearchParameters sp) {
    List<EntitySelector<?, ?, ?>> selectors = sp.getEntities();
    List<Predicate> predicates = newArrayList();

    for (EntitySelector<?, ?, ?> s : selectors) {
      @SuppressWarnings("unchecked")
      EntitySelector<? super E, ? extends Identifiable<?>, ?> selector =
          (EntitySelector<? super E, ? extends Identifiable<?>, ?>) s;

      if (selector.isNotEmpty()) {
        List<Predicate> selectorPredicates = newArrayList();

        for (Identifiable<?> selection : selector.getSelected()) {
          selectorPredicates.add(builder.equal(getExpression(root, selector), selection.getId()));
        }

        if (TRUE == selector.getIncludeNull()) {
          selectorPredicates.add(builder.or(builder.isNull(getExpression(root, selector))));
        }

        predicates.add(JpaUtil.orPredicate(builder, selectorPredicates));
      } else if (selector.isIncludeNullSet()) {
        if (selector.getIncludeNull()) {
          predicates.add(builder.isNull(getExpression(root, selector)));
        } else {
          predicates.add(builder.isNotNull(getExpression(root, selector)));
        }
      }
    }

    return JpaUtil.concatPredicate(sp, builder, predicates);
  }