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

项目:plumdo-work    文件:SimpleExpression.java   
@SuppressWarnings({ "rawtypes", "unchecked" })  
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query,  
        CriteriaBuilder builder) {  
    Path expression = null;  
    if(fieldName.contains(".")){  
        String[] names = StringUtils.split(fieldName, ".");  
        expression = root.get(names[0]);  
        for (int i = 1; i < names.length; i++) {  
            expression = expression.get(names[i]);  
        }  
    }else{  
        expression = root.get(fieldName);  
    }  

    switch (operator) {  
    case EQ:  
        return builder.equal(expression, value);  
    case NE:  
        return builder.notEqual(expression, value);  
    case LIKE:  
        return builder.like((Expression<String>) expression, "%" + value + "%");  
    case LT:  
        return builder.lessThan(expression, (Comparable) value);  
    case GT:  
        return builder.greaterThan(expression, (Comparable) value);  
    case LTE:  
        return builder.lessThanOrEqualTo(expression, (Comparable) value);  
    case GTE:  
        return builder.greaterThanOrEqualTo(expression, (Comparable) value);  
    default:  
        return null;  
    }  
}
项目:OperatieBRP    文件:PredicateBuilderUtil.java   
/**
 * Geef de Path voor de gegeven naam (kan punten bevatten om door objecten te lopen).
 *
 * @param base
 *            basis
 * @param naam
 *            naam
 * @param <T>
 *            attribuut type
 * @return path
 */
public static <T> Path<T> getPath(final Path<?> base, final String naam) {
    final Path<T> result;
    final int index = naam.indexOf('.');
    if (index == -1) {
        result = base.get(naam);
    } else {
        final String part = naam.substring(0, index);
        final String rest = naam.substring(index + 1);

        final Path<?> partPath = base.get(part);
        if (partPath.getModel() == null) {
            // Dan kunnen we hier niet door, maar moeten we via een join
            final Join<?, ?> join = ((From<?, ?>) base).join(part);
            result = getPath(join, rest);
        } else {
            result = getPath(partPath, rest);
        }
    }
    return result;
}
项目:spring-data-examples    文件:CustomerSpecifications.java   
/**
 * All customers with an {@link Account} expiring before the given date.
 * 
 * @param date
 * @return
 */
public static Specification<Customer> accountExpiresBefore(final LocalDate date) {

    return new Specification<Customer>() {

        @Override
        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            Root<Account> accounts = query.from(Account.class);
            Path<Date> expiryDate = accounts.<Date> get("expiryDate");
            Predicate customerIsAccountOwner = cb.equal(accounts.<Customer> get("customer"), root);
            Predicate accountExpiryDateBefore = cb.lessThan(expiryDate, date.toDateTimeAtStartOfDay().toDate());

            return cb.and(customerIsAccountOwner, accountExpiryDateBefore);
        }
    };
}
项目:CriteriaBuilder    文件:CriteriaServiceImpl.java   
private Path<T> fetchNestedPath(Path<T> root, String fieldname) {
    String[] fields = fieldname.split("\\.");
    Path<T> result = null;
    for (String field : fields) {
        if(result == null) {
            result = root.get(field);
        } else {
            result = result.get(field);
        }
    }
    return result;
}
项目:aws-photosharing-example    文件:ServiceFacade.java   
private <T> List<Order> getSort(Root<T> p_root, CriteriaBuilder p_builder, Sort[] p_sort) {

    List<Order> order = new LinkedList<Order>();

    if (p_sort != null && p_sort.length > 0) {              

        for (Sort sort : p_sort) {
            Path<?> property_path = null;       

            for (String hop : sort.getPropertyPath()) {
                if (property_path == null)
                    property_path = p_root.get(hop);
                else
                    property_path = property_path.get(hop);
            }
            if (sort.getOrderAscending()) {
                order.add(p_builder.asc(property_path));
            } else {
                order.add(p_builder.desc(property_path));
            }
        }           
    }

    return order;
}
项目:dev-courses    文件:ToDoListDAO.java   
public void updateTask(final ToDoList pToDoList) {

       final CriteriaBuilder lCriteriaBuilder = entityManager.getCriteriaBuilder();

       //Creation de la requête d'update
       final CriteriaUpdate<ToDoList> lCriteriaUpdate = lCriteriaBuilder.createCriteriaUpdate(ToDoList.class);
       final Root<ToDoList> lRoot = lCriteriaUpdate.from(ToDoList.class);
       final Path<ToDoList> lPath = lRoot.get("id");
       //On utilise la variable pToDoList transmise en parametre de la methode
       final Expression<Boolean> lExpression = lCriteriaBuilder.equal(lPath, pToDoList.getId());
       lCriteriaUpdate.where(lExpression);
       lCriteriaUpdate.set("libelle", pToDoList.getLibelle());

       final Query lQuery = entityManager.createQuery(lCriteriaUpdate);
       final int lRowCount = lQuery.executeUpdate();

       //Si la requête modifie un nombre d'occurrences différent de 1 > erreur
       //Sinon update fait.
       if (lRowCount != 1) {
           final org.hibernate.Query lHQuery = lQuery.unwrap(org.hibernate.Query.class);
           final String lSql = lHQuery.getQueryString();
           throw new RuntimeException("Nombre d'occurences (" + lRowCount + 
                   ") modifiés différent de 1 pour " + lSql);
       }

}
项目:Pedidex    文件:JpaCriteriaHelper.java   
private Path<?> getPath(List<String> fieldNames, Root<T> root) {
    javax.persistence.criteria.Path<?> entity = root;

    for (String fieldName : fieldNames) {
        Path<Object> fieldAsPath = entity.get(fieldName);
        if ( Collection.class.isAssignableFrom( fieldAsPath.getJavaType() ) ) {
            if ( ! joinsMap.containsKey(fieldAsPath) ) {
                joinsMap.put(fieldAsPath, ((From<?, ?>) entity).join(fieldName));
            }
            entity = joinsMap.get(fieldAsPath);
        } else {
            entity = entity.get(fieldName);
        }
    }

    return entity;
}
项目:oma-riista-web    文件:PublicHarvestSeasonFeature.java   
private Map<Long, Integer> fetchUsedQuotas() {
    final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Tuple> query = builder.createTupleQuery();
    final Root<HarvestReport> root = query.from(HarvestReport.class);

    Join<Harvest, HarvestQuota> joinedQuotas = root.join(HarvestReport_.harvests).join(Harvest_.harvestQuota, JoinType.LEFT);
    Path<Long> quotaId = joinedQuotas.get(HarvestQuota_.id);

    Expression<Long> count = builder.count(root.get(HarvestReport_.id));

    Predicate onlyApproved = builder.equal(root.get(HarvestReport_.state), HarvestReport.State.APPROVED);
    Predicate quotaNotNull = builder.isNotNull(quotaId);

    CriteriaQuery<Tuple> q = query
            .multiselect(quotaId, count)
            .where(onlyApproved, quotaNotNull)
            .groupBy(quotaId);
    return map(entityManager.createQuery(q).getResultList());
}
项目:oma-riista-web    文件:HarvestReportSpecs.java   
public static Specification<HarvestReport> hasEndOfHuntingReportAndFieldsSpeciesIsPermitSpecies(final Long fieldsId) {
    return (root, query, cb) -> {
        final Subquery<Integer> permitQuery = query.subquery(Integer.class);
        final Root<HarvestPermit> permitRoot = permitQuery.from(HarvestPermit.class);

        final ListJoin<HarvestPermit, HarvestPermitSpeciesAmount> speciesAmounts = permitRoot.join(HarvestPermit_.speciesAmounts);
        final Path<GameSpecies> speciesAmountsSpecies = speciesAmounts.get(HarvestPermitSpeciesAmount_.gameSpecies);

        final Subquery<Integer> fieldsQuery = query.subquery(Integer.class);
        final Root<HarvestReportFields> fieldsRoot = fieldsQuery.from(HarvestReportFields.class);

        final Predicate permitSpeciesEqualToFieldsSpecies = cb.and(
                cb.equal(fieldsRoot.get(HarvestReportFields_.id), fieldsId),
                cb.equal(fieldsRoot.get(HarvestReportFields_.species), speciesAmountsSpecies));
        final Predicate fieldsExists = cb.exists(fieldsQuery.select(cb.literal(1)).where(permitSpeciesEqualToFieldsSpecies));

        return cb.exists(permitQuery
                .select(cb.literal(1))
                .where(cb.and(
                        cb.equal(permitRoot.join(HarvestPermit_.endOfHuntingReport), permitQuery.correlate(root)),
                        fieldsExists))
        );
    };
}
项目:oma-riista-web    文件:JpaPreds.java   
@Nonnull
public static Predicate withinInterval(
        @Nonnull final CriteriaBuilder cb,
        @Nonnull final Path<Date> path,
        @Nullable final LocalDate beginDate,
        @Nullable final LocalDate endDate) {

    Date _endDate = null;

    if (endDate != null) {
        if (beginDate != null) {
            Preconditions.checkArgument(!beginDate.isAfter(endDate), "beginDate must not be after endDate");
        }

        _endDate = DateUtil.toDateNullSafe(endDate.plusDays(1));
    }

    final Date _beginDate = DateUtil.toDateNullSafe(beginDate);

    return withinInterval(cb, path, _beginDate, _endDate);
}
项目:oma-riista-web    文件:JpaPreds.java   
@Nonnull
public static Predicate withinInterval(
        @Nonnull final CriteriaBuilder cb,
        @Nonnull final Path<Date> path,
        @Nullable final Date beginDate,
        @Nullable final Date endDate) {

    Objects.requireNonNull(cb, "cb must not be null");
    Objects.requireNonNull(path, "path must not be null");

    final Predicate dateNotNull = cb.isNotNull(path);

    if (beginDate == null && endDate == null) {
        return dateNotNull;
    }
    if (beginDate == null) {
        return cb.and(dateNotNull, cb.lessThan(path, endDate));
    }
    if (endDate == null) {
        return cb.and(dateNotNull, cb.greaterThanOrEqualTo(path, beginDate));
    }

    return cb.and(dateNotNull, cb.greaterThanOrEqualTo(path, beginDate), cb.lessThan(path, endDate));
}
项目:oma-riista-web    文件:JpaPreds.java   
@Nonnull
public static Predicate withinInterval(
        @Nonnull final CriteriaBuilder cb,
        @Nonnull final Path<LocalDate> beginDate,
        @Nonnull final Path<LocalDate> endDate,
        @Nonnull final LocalDate dateOfInterest) {

    Objects.requireNonNull(cb, "cb must not be null");
    Objects.requireNonNull(beginDate, "beginDate must not be null");
    Objects.requireNonNull(endDate, "endDate must not be null");
    Objects.requireNonNull(dateOfInterest, "dateOfInterest must not be null");

    return cb.or(
            cb.and(cb.isNull(beginDate), cb.or(cb.isNull(endDate), cb.greaterThanOrEqualTo(endDate, dateOfInterest))),
            cb.and(cb.isNull(endDate), cb.lessThanOrEqualTo(beginDate, dateOfInterest)),
            cb.and(cb.lessThanOrEqualTo(beginDate, dateOfInterest), cb.greaterThanOrEqualTo(endDate, dateOfInterest))
    );
}
项目:oma-riista-web    文件:JpaPreds.java   
@Nonnull
public static Predicate withinHuntingYear(
        @Nonnull final Path<Date> date,
        @Nonnull final Expression<Integer> huntingYear,
        @Nonnull final CriteriaBuilder cb) {

    final Expression<Integer> year = cb.function("year", Integer.class, date);
    final Expression<Integer> month = cb.function("month", Integer.class, date);

    final Predicate currentHuntingYearBeganLastYear = cb.lessThan(month, DateUtil.HUNTING_YEAR_BEGIN_MONTH);

    return cb.and(
            cb.isNotNull(date),
            cb.isNotNull(huntingYear),
            cb.or(
                    cb.and(cb.equal(year, huntingYear), cb.not(currentHuntingYearBeganLastYear)),
                    cb.and(cb.equal(year, cb.sum(huntingYear, 1)), currentHuntingYearBeganLastYear)));
}
项目:memorise    文件:JpaUserDao.java   
@Override
@Transactional(readOnly = true)
public User findByName(String name) {
    final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
    final CriteriaQuery<User> criteriaQuery = builder.createQuery(this.entityClass);

    Root<User> root = criteriaQuery.from(this.entityClass);
    Path<String> namePath = root.get("name");
    criteriaQuery.where(builder.equal(namePath, name));

    TypedQuery<User> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
    List<User> users = typedQuery.getResultList();

    if (users.isEmpty()) {
        return null;
    }

    return users.iterator().next();
}
项目:rpb    文件:ByExampleUtil.java   
/**
 * Add a predicate for each simple property whose value is not null.
 */
public <T> List<Predicate> byExample(ManagedType<T> mt, Path<T> mtPath, final T mtValue, SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE //
                || attr.getPersistentAttributeType() == ONE_TO_ONE //
                || attr.getPersistentAttributeType() == EMBEDDED) {
            continue;
        }

        Object attrValue = getValue(mtValue, attr);
        if (attrValue != null) {
            if (attr.getJavaType() == String.class) {
                if (isNotEmpty((String) attrValue)) {
                    predicates.add(JpaUtil.stringPredicate(mtPath.get(stringAttribute(mt, attr)), attrValue, sp, builder));
                }
            } else {
                predicates.add(builder.equal(mtPath.get(attribute(mt, attr)), attrValue));
            }
        }
    }
    return predicates;
}
项目:rpb    文件:ByExampleUtil.java   
/**
 * Invoke byExample method for each not null x-to-one association when their pk is not set. This allows you to search entities based on an associated
 * entity's properties value.
 */
@SuppressWarnings("unchecked")
public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(ManagedType<T> mt, Root<T> mtPath, final T mtValue,
        SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { //
            M2O m2oValue = (M2O) getValue(mtValue, mt.getAttribute(attr.getName()));
            if (m2oValue != null && !m2oValue.isIdSet()) {
                Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
                ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
                Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
                predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
            }
        }
    }
    return predicates;
}
项目:code-examples    文件:UserService.java   
private Specification<User> getFilterSpecification(Map<String, String> filterValues) {
    return (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> {
        Optional<Predicate> predicate = filterValues.entrySet().stream()
                .filter(v -> v.getValue() != null && v.getValue().length() > 0)
                .map(entry -> {
                    Path<?> path = root;
                    String key = entry.getKey();
                    if (entry.getKey().contains(".")) {
                        String[] splitKey = entry.getKey().split("\\.");
                        path = root.join(splitKey[0]);
                        key = splitKey[1];
                    }
                    return builder.like(path.get(key).as(String.class), "%" + entry.getValue() + "%");
                })
                .collect(Collectors.reducing((a, b) -> builder.and(a, b)));
        return predicate.orElseGet(() -> alwaysTrue(builder));
    };
}
项目:katharsis-framework    文件:ComputedAttributeCriteriaTest.java   
@Override
protected JpaQueryFactory createQueryFactory(final EntityManager em) {
    JpaCriteriaQueryFactory factory = JpaCriteriaQueryFactory.newInstance();

    factory.registerComputedAttribute(TestEntity.class, ATTR_VIRTUAL_VALUE, String.class,
            new JpaCriteriaExpressionFactory<From<?, TestEntity>>() {

                @Override
                public Expression<String> getExpression(From<?, TestEntity> parent, CriteriaQuery<?> query) {
                    CriteriaBuilder builder = em.getCriteriaBuilder();
                    Path<String> stringValue = parent.get(TestEntity.ATTR_stringValue);
                    return builder.upper(stringValue);
                }
            });

    return factory;
}
项目:oauth-service    文件:PredicateHelper.java   
public static Predicate createSearchPredicate(final CriteriaBuilder cb,
                                              final String search,
                                              final Path<String>... paths) {
    if (isBlank(search)) {
        return cb.and();
    }

    if (paths == null || paths.length == 0) {
        return cb.or();
    }

    return cb.and(
            Stream.of(search.split("\\s+"))
                    .filter(StringUtils::isNotBlank)
                    .map(String::trim)
                    .map(str ->
                            cb.or(
                                    Stream.of(paths)
                                            .map(path -> cb.like(path, "%" + str + "%"))
                                            .toArray(Predicate[]::new)
                            )
                    )
                    .toArray(Predicate[]::new)
    );
}
项目:metaworks_framework    文件:BetweenDatePredicateProvider.java   
@Override
public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root,
                                String ceilingEntity, String fullPropertyName, Path<Comparable> explicitPath,
                                List<Comparable> directValues) {
    Path<Comparable> path;
    if (explicitPath != null) {
        path = explicitPath;
    } else {
        path = fieldPathBuilder.getPath(root, fullPropertyName, builder);
    }
    if (directValues.size() == 2) {
        if (directValues.get(0) == null) {
            return builder.lessThan(path, directValues.get(1));
        } else if (directValues.get(1) == null) {
            return builder.greaterThanOrEqualTo(path, directValues.get(0));
        }
        return builder.between(path, directValues.get(0), directValues.get(1));
    } else {
        // The user passed in a single date which is only down to the second granularity. The database stores things
        // down to the millisecond, so we can't just do equals we have to filter dates between the date provided and
        // 1000 milliseconds later than the date provided to get all records for that particular second
        Date secondFromNow = new Date(((Date)directValues.get(0)).getTime() + 1000);
        return builder.between(path, directValues.get(0), secondFromNow);
    }
}
项目:metaworks_framework    文件:Restriction.java   
/**
 * This method  will return a FieldPathBuilder that could be used by the caller to establish any additional Roots that 
 * might be necessary due to the path living inside of a polymorphic version of the ceiling entity. The Predicate 
 * object that {@link #buildRestriction(...)} returns is also available inside of the FieldPathBuilder object for 
 * the caller's use.
 * 
 * @param builder
 * @param root
 * @param ceilingEntity
 * @param targetPropertyName
 * @param explicitPath
 * @param directValues
 * @param shouldConvert
 * @return
 */
public Predicate buildRestriction(CriteriaBuilder builder, From root, String ceilingEntity, String targetPropertyName, 
        Path explicitPath, List directValues, boolean shouldConvert, CriteriaQuery criteria, List<Predicate> restrictions) {
    fieldPathBuilder.setCriteria(criteria);
    fieldPathBuilder.setRestrictions(restrictions);
    List<Object> convertedValues = new ArrayList<Object>();
    if (shouldConvert && filterValueConverter != null) {
        for (Object item : directValues) {
            String stringItem = (String) item;
            convertedValues.add(filterValueConverter.convert(stringItem));
        }
    } else {
        convertedValues.addAll(directValues);
    }

    return predicateProvider.buildPredicate(builder, fieldPathBuilder, root, ceilingEntity, targetPropertyName,
            explicitPath, convertedValues);
}
项目:hawkbit    文件:RSQLUtility.java   
private Object convertValueIfNecessary(final ComparisonNode node, final A fieldName, final String value,
        final Path<Object> fieldPath) {
    // in case the value of an rsql query e.g. type==application is an
    // enum we need to handle it separately because JPA needs the
    // correct java-type to build an expression. So String and numeric
    // values JPA can do it by it's own but not for classes like enums.
    // So we need to transform the given value string into the enum
    // class.
    final Class<? extends Object> javaType = fieldPath.getJavaType();
    if (javaType != null && javaType.isEnum()) {
        return transformEnumValue(node, value, javaType);
    }
    if (fieldName instanceof FieldValueConverter) {
        return convertFieldConverterValue(node, fieldName, value);
    }

    if (Boolean.TYPE.equals(javaType)) {
        return convertBooleanValue(node, value, javaType);
    }

    return value;
}
项目:rpb    文件:ByExampleUtil.java   
/**
 * Invoke byExample method for each not null x-to-one association when their pk is not set. This allows you to search entities based on an associated
 * entity's properties value.
 */
@SuppressWarnings("unchecked")
public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(ManagedType<T> mt, Root<T> mtPath, final T mtValue,
        SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { //
            M2O m2oValue = (M2O) getValue(mtValue, mt.getAttribute(attr.getName()));
            if (m2oValue != null && !m2oValue.isIdSet()) {
                Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
                ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
                Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
                predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
            }
        }
    }
    return predicates;
}
项目:javaee-lab    文件:ByPropertySelectorUtil.java   
private <E> void byStringSelector(Root<E> root, CriteriaBuilder builder, List<Predicate> predicates, SearchParameters sp,
                                  PropertySelector<? super E, String> selector) {
    if (selector.isNotEmpty()) {
        List<Predicate> selectorPredicates = newArrayList();

        for (String selection : selector.getSelected()) {
            Path<String> path = jpaUtil.getPath(root, selector.getAttributes());
            selectorPredicates.add(jpaUtil.stringPredicate(path, selection, selector.getSearchMode(), sp, builder));
        }
        if (selector.isOrMode()) {
            predicates.add(jpaUtil.orPredicate(builder, selectorPredicates));
        } else {
            predicates.add(jpaUtil.andPredicate(builder, selectorPredicates));
        }
    }
}
项目:herd    文件:TagDaoImpl.java   
@Override
public List<TagEntity> getTags()
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TagEntity> criteria = builder.createQuery(TagEntity.class);

    // The criteria root is the tag entity.
    Root<TagEntity> tagEntityRoot = criteria.from(TagEntity.class);

    // Join on the other tables we can filter on.
    Join<TagEntity, TagTypeEntity> tagTypeEntityJoin = tagEntityRoot.join(TagEntity_.tagType);

    // Get the columns.
    Path<String> displayNameColumn = tagEntityRoot.get(TagEntity_.displayName);
    Path<Integer> tagTypeOrderNumberColumn = tagTypeEntityJoin.get(TagTypeEntity_.orderNumber);
    Path<String> tagTypeCodeColumn = tagTypeEntityJoin.get(TagTypeEntity_.code);

    // Add all clauses to the query.
    criteria.select(tagEntityRoot).orderBy(builder.asc(tagTypeOrderNumberColumn), builder.asc(tagTypeCodeColumn), builder.asc(displayNameColumn));

    // Run the query to get the results.
    return entityManager.createQuery(criteria).getResultList();
}
项目:montgomery    文件:JpaUserDao.java   
@Override
@Transactional(readOnly = true)
public User findByName(String name) {
    final CriteriaBuilder builder = this.getEntityManager()
            .getCriteriaBuilder();
    final CriteriaQuery<User> criteriaQuery = builder
            .createQuery(this.entityClass);

    Root<User> root = criteriaQuery.from(this.entityClass);
    Path<String> namePath = root.get("name");
    criteriaQuery.where(builder.equal(namePath, name));

    TypedQuery<User> typedQuery = this.getEntityManager().createQuery(
            criteriaQuery);
    List<User> users = typedQuery.getResultList();

    if (users.isEmpty()) {
        return null;
    }

    return users.iterator().next();
}
项目:actionbazaar    文件:ItemManager.java   
public List<Tuple> getWinningBidTuple(Long itemId) {
   CriteriaBuilder builder = entityManager.getCriteriaBuilder();
   CriteriaQuery<Tuple> query = builder.createTupleQuery();
   Root<Item> itemRoot = query.from(Item.class);
   Root<Order> orderRoot = query.from(Order.class);
   Root<Bid> bidRoot = query.from(Bid.class);
   Root<BazaarAccount> userRoot = query.from(BazaarAccount.class);
   Join<Order,Bid> j1 = orderRoot.join(Order_.bid);
   Join<Order,Item> j2 = orderRoot.join(Order_.item);
   Join<Order,BazaarAccount> j3 = orderRoot.join(Order_.bidder);
   Path<Long> itemIdPath = itemRoot.get(Item_.itemId);
   Predicate itemPredicate = builder.equal(itemIdPath,itemId);
   query.multiselect( 
           userRoot.get( BazaarAccount_.username ), 
           bidRoot.get( Bid_.bidPrice ),
           itemRoot.get(Item_.itemName) ,
           itemRoot.get(Item_.description));
   TypedQuery<Tuple> q = entityManager.createQuery(query);
   query.where(itemPredicate); 

   List<Tuple> results = q.getResultList();
   for(Tuple result : results) {
       logger.log(Level.INFO, "Item: {0}", result.get(itemRoot.get(Item_.itemName)));
   }
   return q.getResultList();
}
项目:opencucina    文件:ProcessTokenRepositoryImpl.java   
/**
 * JAVADOC Method Level Comments
 *
 * @param wfid JAVADOC.
 *
 * @return JAVADOC.
 */
@Override
public Collection<ProcessToken> findByProcessDefinitionId(String wfid) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> tcq = cb.createTupleQuery();
    Root<ProcessToken> rt = tcq.from(ProcessToken.class);
    Predicate tokp = cb.equal(rt.get("processDefinitionId"), wfid);
    Path<Object> pid = rt.get("domainObjectId");

    Root<EntityDescriptor> rc = tcq.from(EntityDescriptor.class);
    Predicate clap = cb.equal(pid, rc.get("localId"));

    tcq.multiselect(rt, rc).where(cb.and(clap, tokp));

    Collection<Tuple> results = entityManager.createQuery(tcq).getResultList();

    if ((results == null) || (results.size() == 0)) {
        LOG.warn("Failed to find workflow instances for the workflowId:" + wfid);

        return Collections.emptyList();
    }

    return populate(results);
}
项目:opencucina    文件:MessageRepositoryImplTest.java   
/**
 * JAVADOC Method Level Comments
 */
@SuppressWarnings("unchecked")
@Test
public void testFindByBasename() {
    Root<Message> root = mock(Root.class);

    when(cq.from(Message.class)).thenReturn(root);

    Path<Object> pathb = mock(Path.class);

    when(root.get("baseName")).thenReturn(pathb);

    Predicate preb = mock(Predicate.class);

    when(cb.equal(pathb, "basename")).thenReturn(preb);
    when(cq.where(preb)).thenReturn(cq);

    repo.findByBasename("basename");
    verify(tq).getResultList();
}
项目:opencucina    文件:MessageRepositoryImplTest.java   
/**
 * JAVADOC Method Level Comments
 */
@SuppressWarnings("unchecked")
@Test
public void testFindByCode() {
    Root<Message> root = mock(Root.class);

    when(cq.from(Message.class)).thenReturn(root);

    Path<Object> pathb = mock(Path.class);

    when(root.get("messageCd")).thenReturn(pathb);

    Predicate preb = mock(Predicate.class);

    when(cb.equal(pathb, "code")).thenReturn(preb);
    when(cq.where(preb)).thenReturn(cq);

    repo.findByCode("code");
    verify(tq).getResultList();
}
项目:kc-rice    文件:NativeJpaQueryTranslator.java   
/**
 * Translates the Rice Criteria API {@link PropertyPath} object into a native JPA path which can be used in JPA
 * predicates.
 * 
 * @param criteria
 *            The base criteria context for translation of the property if no specific data type is given.
 * @param value
 *            The {@link PropertyPath} object passed in from the Rice Criteria API.
 * @return A JPA {@link Path} object which can be used in JPA {@link Predicate} statements.
 */
@SuppressWarnings("rawtypes")
protected Path translatePropertyPathIntoJpaPath(TranslationContext criteria, PropertyPath value) {
    TranslationContext tempCriteria = criteria;
    if (value.getDataType() != null) {
        try {
            tempCriteria = createCriteria(Class.forName(value.getDataType()));
        } catch (ClassNotFoundException e) {
            // unable to find the type - ignore and attempt to resolve path without special context
            Logger.getLogger(this.getClass()).error(
                    "Unable to find data type " + value.getDataType()
                            + ".  Falling back to the base root for the query: " + criteria.root.getJavaType());
        }
    }
    return tempCriteria.attr(value.getPropertyPath());
}
项目:herd    文件:BaseJpaDaoImpl.java   
/**
 * Gets an "in" clause predicate for a list of values. This will take care of breaking the list of values into a group of sub-lists where each sub-list is
 * placed in a separate "in" clause and all "in" clauses are "or"ed together. The size of each sub-list is obtained through an environment configuration.
 *
 * @param builder the criteria builder.
 * @param path the path to the field that is being filtered.
 * @param values the list of values to place in the in clause.
 * @param <T> the type referenced by the path.
 *
 * @return the predicate for the in clause.
 */
protected <T> Predicate getPredicateForInClause(CriteriaBuilder builder, Path<T> path, List<T> values)
{
    // Get the chunk size from the environment and use a default as necessary.
    int inClauseChunkSize = configurationHelper.getProperty(ConfigurationValue.DB_IN_CLAUSE_CHUNK_SIZE, Integer.class);

    // Initializes the returned predicate and the value list size.
    Predicate predicate = null;
    int listSize = values.size();

    // Loop through each chunk of values until we have reached the end of the values.
    for (int i = 0; i < listSize; i += inClauseChunkSize)
    {
        // Get a sub-list for the current chunk of data.
        List<T> valuesSubList = values.subList(i, (listSize > (i + inClauseChunkSize) ? (i + inClauseChunkSize) : listSize));

        // Get an updated predicate which will be the "in" clause of the sub-list on the first loop or the "in" clause of the sub-list "or"ed with the\
        // previous sub-list "in" clause.
        predicate = (predicate == null ? path.in(valuesSubList) : builder.or(predicate, path.in(valuesSubList)));
    }

    // Return the "in" clause predicate.
    return predicate;
}
项目:SparkCommerce    文件:FieldPathBuilder.java   
public FieldPath getFieldPath(From root, String fullPropertyName) {
    String[] pieces = fullPropertyName.split("\\.");
    List<String> associationPath = new ArrayList<String>();
    List<String> basicProperties = new ArrayList<String>();
    int j = 0;
    for (String piece : pieces) {
        checkPiece: {
            if (j == 0) {
                Path path = root.get(piece);
                if (path instanceof PluralAttributePath) {
                    associationPath.add(piece);
                    break checkPiece;
                }
            }
            basicProperties.add(piece);
        }
        j++;
    }
    FieldPath fieldPath = new FieldPath()
        .withAssociationPath(associationPath)
        .withTargetPropertyPieces(basicProperties);

    return fieldPath;
}
项目:SparkCommerce    文件:Restriction.java   
/**
 * This method  will return a FieldPathBuilder that could be used by the caller to establish any additional Roots that 
 * might be necessary due to the path living inside of a polymorphic version of the ceiling entity. The Predicate 
 * object that {@link #buildRestriction(...)} returns is also available inside of the FieldPathBuilder object for 
 * the caller's use.
 * 
 * @param builder
 * @param root
 * @param ceilingEntity
 * @param targetPropertyName
 * @param explicitPath
 * @param directValues
 * @param shouldConvert
 * @return
 */
public Predicate buildRestriction(CriteriaBuilder builder, From root, String ceilingEntity, String targetPropertyName, 
        Path explicitPath, List directValues, boolean shouldConvert, CriteriaQuery criteria, List<Predicate> restrictions) {
    fieldPathBuilder.setCriteria(criteria);
    fieldPathBuilder.setRestrictions(restrictions);
    List<Object> convertedValues = new ArrayList<Object>();
    if (shouldConvert && filterValueConverter != null) {
        for (Object item : directValues) {
            String stringItem = (String) item;
            convertedValues.add(filterValueConverter.convert(stringItem));
        }
    } else {
        convertedValues.addAll(directValues);
    }

    return predicateProvider.buildPredicate(builder, fieldPathBuilder, root, ceilingEntity, targetPropertyName,
            explicitPath, convertedValues);
}
项目:sucok-framework    文件:QueryFormHelper.java   
public static <X, T> Expression<X> getPath(Root<T> root, String name) {
    String[] array = name.split("[.]");
    Expression<X> expr = root.get(array[0]);
    for (int i = 1; i < array.length; i++) {
        expr = ((Path<X>) expr).get(array[i]);
    }
    return expr;
}
项目:plumdo-stock    文件:SimpleExpression.java   
@SuppressWarnings({ "rawtypes", "unchecked" })  
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query,  
        CriteriaBuilder builder) {  
    Path expression = null;  
    if(fieldName.contains(".")){  
        String[] names = StringUtils.split(fieldName, ".");  
        expression = root.get(names[0]);  
        for (int i = 1; i < names.length; i++) {  
            expression = expression.get(names[i]);  
        }  
    }else{  
        expression = root.get(fieldName);  
    }  

    switch (operator) {  
    case EQ:  
        return builder.equal(expression, value);  
    case NE:  
        return builder.notEqual(expression, value);  
    case LIKE:  
        return builder.like((Expression<String>) expression, "%" + value + "%");  
    case LT:  
        return builder.lessThan(expression, (Comparable) value);  
    case GT:  
        return builder.greaterThan(expression, (Comparable) value);  
    case LTE:  
        return builder.lessThanOrEqualTo(expression, (Comparable) value);  
    case GTE:  
        return builder.greaterThanOrEqualTo(expression, (Comparable) value);  
    default:  
        return null;  
    }  
}
项目:endpoint-health    文件:EndPointCheckDao.java   
public Collection<EndPointCheck> findByDateRange(final EndPoint endPoint, final Date startDate,
        final Date endDate) {
    final CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    final CriteriaQuery<EndPointCheck> criteriaQuery = criteriaBuilder.createQuery(getEntityClass());
    final Root<EndPointCheck> root = criteriaQuery
            .from(getEntityManager().getMetamodel().entity(getEntityClass()));

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

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

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

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

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

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

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

    return getEntityManager().createQuery(criteriaQuery)
            .setParameter(endPointParameter, endPoint)
            .setParameter(startDateParameter, startDate, TemporalType.DATE)
            .setParameter(endDateParameter, endDate, TemporalType.DATE)
            .getResultList();
}
项目:CriteriaBuilder    文件:CriteriaServiceImpl.java   
protected Predicate buildPredicateWithOperator(Path<T> tt, Conjunctions conjunctions, List<Predicate> predicateList) {
    CriteriaBuilder criteriaBuilder = this.entitymanager.getCriteriaBuilder();
    Predicate predicate = null;
    if(conjunctions.equals(Conjunctions.AND)) {
        predicate = criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
    } else if(conjunctions.equals(Conjunctions.OR)) {
        predicate = criteriaBuilder.or(predicateList.toArray(new Predicate[predicateList.size()]));
    }
    return predicate;
}
项目:CriteriaBuilder    文件:CriteriaServiceImpl.java   
@SuppressWarnings ({ "unchecked", "rawtypes" })
protected Predicate buildPredicate(Path<T> root, SearchField field)
{
    Path<T> tt = (!field.getField().contains(".")) ? root.get(field.getField()) : fetchNestedPath(root, field.getField());
    CriteriaBuilder criteriaBuilder = this.entitymanager.getCriteriaBuilder();

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

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

    Object valueObject = convertStringValueToObject(field.getValue(), javaType);
    switch (field.getOperator())
    {
        case GE:
            return criteriaBuilder.greaterThan((Expression) tt, (Comparable) valueObject);
        case GTE:
            return criteriaBuilder.greaterThanOrEqualTo((Expression) tt, (Comparable) valueObject);
        case LE:
            return criteriaBuilder.lessThan((Expression) tt, (Comparable) valueObject);
        case LTE:
            return criteriaBuilder.lessThanOrEqualTo((Expression) tt, (Comparable) valueObject);
        case NE: 
               return criteriaBuilder.notEqual(tt, valueObject); 
        case EX:
            return criteriaBuilder.like((Expression) tt, "%"+field.getValue()+"%");
        default:
        {
            //EQ
            return criteriaBuilder.equal(tt, valueObject);
        }
    }
}
项目:aws-photosharing-example    文件:ServiceFacade.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private <C,T> Predicate getIsMemberOfPredicate(Root<C> p_root, CriteriaBuilder p_builder, Filter p_filter) {
    if (p_filter == null)
        return null;

    Path<? extends Collection> property_path = null;    

    for (String hop : p_filter.getPropertyPath()) {
        if (property_path == null)
            property_path = p_root.get(hop);
        else
            property_path = property_path.get(hop);
    }       
    return p_builder.isMember(p_filter.getValue(), property_path);
}