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; }
@Override public Set<String> getTagsSuggest(String url) { String hashUrl = MD5Util.md5Hex(url); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> query = cb.createTupleQuery(); Root<Bookmark> root = query.from(Bookmark.class); // joins SetJoin<Bookmark, String> tagsJoin = root.joinSet("tags"); query.select(cb.tuple(tagsJoin.alias("tag"), cb.count(tagsJoin).alias("count_tags"))); query.where(cb.equal(root.get("hashUrl"), hashUrl)); query.groupBy(tagsJoin); query.orderBy(cb.desc(cb.count(tagsJoin))); // top five tags List<Tuple> result = entityManager.createQuery(query).setMaxResults(5).getResultList(); Set<String> topTags = new HashSet<String>(); for (Tuple t : result) { topTags.add((String) t.get("tag")); } return topTags; }
/** * 废弃 * * @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; }
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; }
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()); }
/** This test provides a demonstration for using the ANY subquery result evaluation */ @Test public void testAny() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Clerk> qdef = cb.createQuery(Clerk.class); Root<Clerk> c = qdef.from(Clerk.class); qdef.select(c); // select c from Clerk c // where 125 < ANY " + // (select s.amount from c.sales s)", Subquery<BigDecimal> sqdef = qdef.subquery(BigDecimal.class); Root<Clerk> c1 = sqdef.from(Clerk.class); Join<Clerk, Sale> s = c1.join("sales"); sqdef.select(s.<BigDecimal>get("amount")).where(cb.equal(c, c1)); Predicate p1 = cb.lessThan(cb.literal(new BigDecimal(125)), cb.any(sqdef)); qdef.where(p1); List<Clerk> results1 = executeQuery(qdef); assertEquals("unexpected number of rows", 2, results1.size()); // select c from Clerk c // where 125 > ANY // (select s.amount from c.sales s) Predicate p2 = cb.greaterThan(cb.literal(new BigDecimal(125)), cb.any(sqdef)); qdef.where(p2); List<Clerk> results2 = executeQuery(qdef); assertEquals("unexpected number of rows", 1, results2.size()); }
@Override public List<Train> find(TrainFilter trainFilter) { EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Train> cq = cb.createQuery(Train.class); Root<Train> from = cq.from(Train.class); cq.select(from); if (trainFilter.getId() != null) { Predicate idEqual = cb.equal(from.get(Train_.id), trainFilter.getId()); cq.where(cb.and(idEqual)); } if (trainFilter.getName() != null) { Predicate idEqual = cb.equal(from.get(Train_.id), trainFilter.getName()); cq.where(cb.and(idEqual)); } if (trainFilter.getSortProperty() != null) { cq.orderBy(new OrderImpl(from.get(trainFilter.getSortProperty()), trainFilter.isSortOrder())); } TypedQuery<Train> q = em.createQuery(cq); if (trainFilter.getOffset() != null && trainFilter.getLimit() != null) { q.setFirstResult(trainFilter.getOffset()); q.setMaxResults(trainFilter.getLimit()); } List<Train> allitems = q.getResultList(); return allitems; }
/** This test method demonstrates using date functions. */ @Test public void testDates() { log.info("*** testDates() ***"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Sale> qdef = cb.createQuery(Sale.class); Root<Sale> s = qdef.from(Sale.class); qdef.select(s); // select s from Sale s // where s.date < CURRENT_DATE qdef.where(cb.lessThan(s.<Date>get("date"), cb.currentDate())); int rows = executeQuery(qdef).size(); assertEquals("unexpected number of rows", 2, rows); // select s from Sale s // where s.date = CURRENT_DATE qdef.where(cb.equal(s.<Date>get("date"), cb.currentDate())); rows = executeQuery(qdef).size(); assertEquals("unexpected number of rows", 0, rows); // no bulk query capability in Criteria API rows = em.createQuery("update Sale s " + "set s.date = CURRENT_DATE").executeUpdate(); assertEquals("unexpected number of rows", 2, rows); em.getTransaction().commit(); em.clear(); // remove stale objects in cache // select s from Sale s // where s.date = CURRENT_DATE qdef.where(cb.equal(s.<Date>get("date"), cb.currentDate())); rows = executeQuery(qdef).size(); assertEquals("unexpected number of rows", 2, rows); }
protected <T, T1, T2> PageRequestId<T> findWithSpecification( String requestId, EntityManager entityManager, Pageable pageable, Filter3<T, T1, T2> specification, Class<T> type, Class<T1> type1, Class<T2> type2) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); long total; { CriteriaQuery<Long> cqTotal = builder.createQuery(Long.class); Root<T1> root1 = cqTotal.from(type1); Root<T2> root2 = cqTotal.from(type2); Predicate predicate = specification.toPredicate(root1, root2, cqTotal, builder); if (predicate != null) cqTotal.where(predicate); cqTotal.select(builder.count(root1)); total = entityManager.createQuery(cqTotal).getSingleResult(); } CriteriaQuery<T> cq = builder.createQuery(type); Root<T1> root1 = cq.from(type1); Root<T2> root2 = cq.from(type2); Predicate predicate = specification.toPredicate(root1, root2, cq, builder); if (predicate != null) cq.where(predicate); cq.select(specification.getSelection(root1, root2, cq, builder)); if (pageable.getSort() != null) { List<Order> orders = new LinkedList<Order>(); for (Iterator<org.springframework.data.domain.Sort.Order> itr = pageable.getSort().iterator(); itr.hasNext(); ) { org.springframework.data.domain.Sort.Order order = itr.next(); String sx[] = order.getProperty().split("\\."); Path<Object> p; if (sx[0].equals("t1")) { p = root1.get(sx[1]); } else if (sx[0].equals("t2")) { p = root2.get(sx[1]); } else { throw new RuntimeException("Invalid order " + U.dump(order)); } for (int i = 2, il = sx.length; i < il; i++) p = p.get(sx[i]); if (order.isAscending()) { orders.add(builder.asc(p)); } else { orders.add(builder.desc(p)); } } cq.orderBy(orders); } TypedQuery<T> qry = entityManager.createQuery(cq); qry.setFirstResult(pageable.getOffset()).setMaxResults(pageable.getPageSize()); return new PageRequestIdImpl<T>(qry.getResultList(), pageable, total, requestId); }
public static <T> Long queryEntitiesCount(EntityManager em, Class<T> entity, QueryParameters q) { if (q == null) throw new IllegalArgumentException( "Query parameters can't be null. " + "If you don't have any parameters either pass a empty object or " + "use the queryEntitiesCount(EntityManager, Class<T>) method."); log.finest("Querying entity count: '" + entity.getSimpleName() + "' with parameters: " + q); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<T> r = cq.from(entity); if (!q.getFilters().isEmpty()) { cq.where(createWhereQuery(cb, r, q)); } cq.select(cb.count(r)); return em.createQuery(cq).getSingleResult(); }
@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); }
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()); } }
/** * update the session every time a user makes a request * * @param SID */ private void updatesession(String SID) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Sessiondata> cq = cb.createQuery(Sessiondata.class); Root<Sessiondata> c = cq.from(Sessiondata.class); Predicate condition = cb.equal(c.get("session_id"), SID); cq.where(condition); TypedQuery<Sessiondata> q = em.createQuery(cq); List<Sessiondata> fullList = q.getResultList(); if (fullList.size() == 0) { log.error("Found NO session to updateSession: "); } else { // log.debug("Found session to updateSession: "); Sessiondata sd = fullList.iterator().next(); // log.debug("Found session to updateSession sd "+sd.getUser_id()+" "+sd.getSession_id()); sd.setRefresh_time(new Date()); if (sd.getId() == null) { em.persist(sd); } else { if (!em.contains(sd)) { em.merge(sd); } } } } catch (Exception ex2) { log.error("[updatesession]: ", ex2); } }
public Sessiondata getSessionByHash(String SID) { try { log.debug("updateUser User SID: " + SID); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Sessiondata> cq = cb.createQuery(Sessiondata.class); Root<Sessiondata> c = cq.from(Sessiondata.class); Predicate condition = cb.equal(c.get("session_id"), SID); cq.where(condition); TypedQuery<Sessiondata> q = em.createQuery(cq); List<Sessiondata> fullList = q.getResultList(); if (fullList.size() == 0) { log.error("Could not find session to update: " + SID); return null; } Sessiondata sd = fullList.get(0); return sd; } catch (Exception ex2) { log.error("[updateUser]: ", ex2); } return null; }
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(); }
@Override public final List<Product> findByFeatures(final Map<Integer, List<String>> featureValues) { CriteriaBuilder builder = manager.getCriteriaBuilder(); CriteriaQuery<Product> criteriaQuery = builder.createQuery(Product.class); Root<Product> product = criteriaQuery.from(Product.class); Path<ProductFeature> feature = product.join("features"); CriteriaQuery<Product> select = criteriaQuery.select(product); Predicate featurePredicate = builder.disjunction(); for (final Map.Entry<Integer, List<String>> fValue : featureValues.entrySet()) { Predicate equalFeatureId = builder.equal(feature.get("featureId"), fValue.getKey()); List<String> values = fValue.getValue(); Predicate equalsValues = builder.disjunction(); for (String value : values) { Predicate equalFeatureVal = builder.equal(feature.get("value"), value); equalsValues = builder.or(equalsValues, equalFeatureVal); } featurePredicate = builder.or(featurePredicate, builder.and(equalFeatureId, equalsValues)); } select.where(featurePredicate); select.groupBy(product.get("id")); select.having(builder.equal(builder.count(product), featureValues.size())); TypedQuery<Product> query = manager.createQuery(criteriaQuery); return query.getResultList(); }
@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(); }
@Test public void testParameterInParameterList() { // Yes, this test makes no semantic sense. But the JPA TCK does it... // it causes a problem on Derby, which does not like the form "... where ? in (?,?)" // Derby wants one side or the other to be CAST (I assume so it can check typing). EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery<MultiTypedBasicAttributesEntity> criteria = em.getCriteriaBuilder().createQuery(MultiTypedBasicAttributesEntity.class); criteria.from(MultiTypedBasicAttributesEntity.class); criteria.where( em.getCriteriaBuilder() .in(em.getCriteriaBuilder().parameter(Long.class, "p1")) .value(em.getCriteriaBuilder().parameter(Long.class, "p2")) .value(em.getCriteriaBuilder().parameter(Long.class, "p3"))); TypedQuery<MultiTypedBasicAttributesEntity> query = em.createQuery(criteria); query.setParameter("p1", 1L); query.setParameter("p2", 2L); query.setParameter("p3", 3L); query.getResultList(); em.getTransaction().commit(); em.close(); }
private List<Organization> getTopOrgs() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Organization> query = cb.createQuery(Organization.class); Root<Organization> root = query.from(Organization.class); query.where(cb.isNull(root.get(Organization_.parent))); return em.createQuery(query).getResultList(); }
/** * Search by criteria. * * @param criteria the criteria * @return the list< t> */ protected List<T> searchByCriteria(E criteria) { CriteriaQuery<T> query = getCriteriaBuilder().createQuery(getEntityClass()); Root<T> from = query.from(getEntityClass()); query.select(from); List<Predicate> predicateList = buildConditions(from, criteria); if (predicateList != null) { Predicate[] predicates = new Predicate[predicateList.size()]; predicateList.toArray(predicates); query.where(predicates); } if (criteria.getGroupBy() != null) { query.groupBy(from.get(criteria.getGroupBy())); } if (criteria.getOrderField() != null) { if (criteria.getOrderType() != null && !"".equals(criteria.getOrderType())) { StringTokenizer outerTokenizer = new StringTokenizer(criteria.getOrderField(), ","); StringTokenizer typeTokenizer = new StringTokenizer(criteria.getOrderType(), ","); List<Order> orders = new ArrayList<Order>(); while (outerTokenizer.hasMoreElements()) { String field = (String) outerTokenizer.nextElement(); String type = (String) typeTokenizer.nextElement(); Path ex = null; if (field.indexOf(".") > 0) { StringTokenizer tokenizer = new StringTokenizer(field, "."); while (tokenizer.hasMoreElements()) { String key = (String) tokenizer.nextElement(); if (ex == null) { ex = from.get(key); } else { ex = ex.get(key); } } } else { ex = from.get(field); } if ("desc".equals(type)) { orders.add(getCriteriaBuilder().desc(ex)); } else if ("asc".equals(type)) { orders.add(getCriteriaBuilder().asc(ex)); } } if (orders.size() > 0) { query.orderBy(orders); } } else { query.orderBy(getCriteriaBuilder().desc(from.get(criteria.getOrderField()))); } } TypedQuery<T> typedQuery = getEntityManager().createQuery(query); if (criteria.getStartIndex() != null) { typedQuery.setFirstResult(criteria.getStartIndex()); typedQuery.setMaxResults(criteria.getPageSize()); } else { typedQuery.setFirstResult(0); typedQuery.setMaxResults(rowLimit); } System.out.println("dfjdfjdkfdkfjd" + typedQuery.toString()); return typedQuery.getResultList(); }
/** * 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; }
public Page<Review> findPage( Member member, Product product, Type type, Boolean isShow, Pageable pageable) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Review> criteriaQuery = criteriaBuilder.createQuery(Review.class); Root<Review> root = criteriaQuery.from(Review.class); criteriaQuery.select(root); Predicate restrictions = criteriaBuilder.conjunction(); if (member != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member)); } if (product != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("product"), product)); } if (type == Type.positive) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("score"), 4)); } else if (type == Type.moderate) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Number>get("score"), 3)); } else if (type == Type.negative) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("score"), 2)); } if (isShow != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isShow"), isShow)); } criteriaQuery.where(restrictions); return super.findPage(criteriaQuery, pageable); }
public List<T> findByCriteria(MultivaluedMap<String, String> queryParameters, Class<T> clazz) { List<T> resultsList = null; CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> cq = criteriaBuilder.createQuery(clazz); List<Predicate> andPredicates = new ArrayList<Predicate>(); Root<T> tt = cq.from(clazz); for (Map.Entry<String, List<String>> entry : queryParameters.entrySet()) { List<String> valueList = entry.getValue(); Predicate predicate = null; if (valueList.size() > 1) { // name=value1&name=value&...&name=valueN // value of name is list [value1, value, ..., valueN] // => name=value1 OR name=value OR ... OR name=valueN List<Predicate> orPredicates = new ArrayList<Predicate>(); for (String currentValue : valueList) { Predicate orPredicate = buildPredicate(tt, entry.getKey(), currentValue); orPredicates.add(orPredicate); } predicate = criteriaBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()])); } else { // name=value // value of name is one element list [value] // => name=value predicate = buildPredicate(tt, entry.getKey(), valueList.get(0)); } andPredicates.add(predicate); } cq.where(andPredicates.toArray(new Predicate[andPredicates.size()])); cq.select(tt); TypedQuery<T> q = getEntityManager().createQuery(cq); resultsList = q.getResultList(); return resultsList; }
public Optional<NsiV2Message> findOneForUpdate( NsiV2Message.Role role, NsiV2Message.Type type, String requesterNsa, String providerNsa, String correlationId) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<NsiV2Message> query = cb.createQuery(NsiV2Message.class); Root<NsiV2Message> root = query.from(NsiV2Message.class); query.where( cb.and( cb.equal(root.get(NsiV2Message_.role), role), cb.equal(root.get(NsiV2Message_.type), type), cb.equal(root.get(NsiV2Message_.requesterNsa), requesterNsa), cb.equal(root.get(NsiV2Message_.providerNsa), providerNsa), cb.equal(root.get(NsiV2Message_.correlationId), correlationId))); return entityManager .createQuery(query) .setLockMode(LockModeType.PESSIMISTIC_WRITE) .setMaxResults(1) .getResultList() .stream() .findFirst(); }
private int getNumberOfInstancesEnded(final ProcessIdentifier identifier) { final CriteriaBuilder cb = em.getCriteriaBuilder(); final CriteriaQuery<Long> cq = cb.createQuery(Long.class); final Root<MeasuredProcessInstance> processInstanceRoot = cq.from(MeasuredProcessInstance.class); cq.where( cb.equal( processInstanceRoot .get(MeasuredProcessInstance_.identifier) .get(ProcessInstanceIdentifier_.metricsId), identifier.getMetricsId()), cb.equal( processInstanceRoot .get(MeasuredProcessInstance_.identifier) .get(ProcessInstanceIdentifier_.packageName), identifier.getPackageName()), cb.equal( processInstanceRoot .get(MeasuredProcessInstance_.identifier) .get(ProcessInstanceIdentifier_.processId), identifier.getProcessId()), cb.isNotNull(processInstanceRoot.get(MeasuredProcessInstance_.endingTime))); cq.select(cb.countDistinct(processInstanceRoot)); return em.createQuery(cq).getSingleResult().intValue(); }
/** * Método que obterm uma lista de logradouros com base na chave primária (ID) do bairro. * * @param idBairro Long o identificador do Bairro (chave primária). * @return Set<Logradouro>, sendo a lista de logradouros do bairro * @throws ServicesException caso dê algum erro ao obter a lista de logradouros * @see richard.falconrh.service.LogradouroServices#obterListaPeloIdBairro(Long) */ @Override public Set<Logradouro> obterListaPeloIdBairro(Long idBairro) throws ServicesException { CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Logradouro> criteriaQuery = criteriaBuilder.createQuery(Logradouro.class); Root<Logradouro> from = criteriaQuery.from(Logradouro.class); Predicate restricaoIdBairro = criteriaBuilder.equal(from.get(Logradouro_.bairro).get(Bairro_.id), idBairro); criteriaQuery.where(restricaoIdBairro); TypedQuery<Logradouro> typedQuery = getEntityManager().createQuery(criteriaQuery); Set<Logradouro> lista = new TreeSet<Logradouro>(typedQuery.getResultList()); for (Logradouro l : lista) { l.getNome(); l.getBairro().getNome(); l.getBairro().getId(); l.getBairro().getMunicipio(); l.getBairro().getMunicipio().getId(); l.getBairro().getMunicipio().getNome(); l.getBairro().getMunicipio().getUf(); l.getBairro().getMunicipio().getUf().getNome(); l.getCep(); l.getTipoLogradouro(); } return lista; }
@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(); }
@Override public List<ClassTeacherMap> findClassesBySchoolAndMember( DictSchool school, Member member, ClassStatus classStatus) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<ClassTeacherMap> criteriaQuery = criteriaBuilder.createQuery(ClassTeacherMap.class); Root<ClassTeacherMap> root = criteriaQuery.from(ClassTeacherMap.class); criteriaQuery.select(root); Predicate restrictions = criteriaBuilder.conjunction(); if (school != null) { restrictions = criteriaBuilder.and( restrictions, criteriaBuilder.equal(root.get("dictClass").get("dictSchool"), school)); } if (member != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member)); } if (classStatus != null) { restrictions = criteriaBuilder.and( restrictions, criteriaBuilder.equal(root.get("dictClass").get("classStatus"), classStatus)); } criteriaQuery.where(restrictions); return entityManager .createQuery(criteriaQuery) .setFlushMode(FlushModeType.COMMIT) .getResultList(); }
public int count(List<Filtro> filtros) { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); javax.persistence.criteria.Root<BaseEntity> rt = cq.from(entityClass); CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); if (filtros != null) { ArrayList<Predicate> predicatesList = new ArrayList<>(); for (Filtro filtro : filtros) { switch (filtro.getTipoFiltro()) { case Equals: predicatesList.add(builder.equal(rt.get(filtro.getDescricao()), filtro.getValor())); break; case LessEqual: Path<Date> date = rt.get(filtro.getDescricao()); predicatesList.add(builder.lessThanOrEqualTo(date, ((Date) filtro.getValor()))); break; case GreaterEqual: Path<Date> date2 = rt.get(filtro.getDescricao()); predicatesList.add(builder.greaterThanOrEqualTo(date2, ((Date) filtro.getValor()))); break; default: predicatesList.add(builder.equal(rt.get(filtro.getDescricao()), filtro.getValor())); break; } } cq.where(predicatesList.<Predicate>toArray(new Predicate[predicatesList.size()])); } cq.select(builder.count(rt)); javax.persistence.Query q = getEntityManager().createQuery(cq); return ((Long) q.getSingleResult()).intValue(); }
@Override public Map<String, Long> countTagsByUser(String userName) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> query = cb.createTupleQuery(); Root<Bookmark> root = query.from(Bookmark.class); // joins SetJoin<Bookmark, String> tagsJoin = root.joinSet("tags"); Join<Bookmark, User> userJoin = root.join("user"); query.select(cb.tuple(tagsJoin.alias("tag"), cb.count(tagsJoin).alias("count_tags"))); query.where(cb.equal(userJoin.get("userName"), userName)); query.groupBy(tagsJoin); query.orderBy(cb.desc(cb.count(tagsJoin))); List<Tuple> result = entityManager.createQuery(query).setMaxResults(30).getResultList(); Map<String, Long> tagRanking = new TreeMap<String, Long>(); for (Tuple t : result) { tagRanking.put((String) t.get("tag"), (Long) t.get("count_tags")); } return tagRanking; }