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

项目: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;
}
项目: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    文件:CriteriaUtils.java   
@SuppressWarnings("unchecked")
@Nonnull
public static <T, U> Join<T, U> join(
        @Nonnull final From<?, T> from, @Nonnull final PluralAttribute<? super T, ?, U> attribute) {

    Objects.requireNonNull(from, "from is null");
    Objects.requireNonNull(attribute, "attribute is null");

    if (attribute instanceof CollectionAttribute) {
        return from.join((CollectionAttribute<T, U>) attribute);
    }
    if (attribute instanceof SetAttribute) {
        return from.join((SetAttribute<T, U>) attribute);
    }
    if (attribute instanceof ListAttribute) {
        return from.join((ListAttribute<T, U>) attribute);
    }
    if (attribute instanceof MapAttribute) {
        return from.join((MapAttribute<T, ?, U>) attribute);
    }

    // Should never end up here.
    throw new IllegalArgumentException();
}
项目: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;
}
项目:jpa-spec    文件:EqualSpecification.java   
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    From from = getRoot(property, root);
    String field = getProperty(property);
    if (values == null) {
        return cb.isNull(from.get(field));
    }
    if (values.length == 1) {
        return getPredicate(from, cb, values[0], field);
    }

    Predicate[] predicates = new Predicate[values.length];
    for (int i = 0; i < values.length; i++) {
        predicates[i] = getPredicate(root, cb, values[i], field);
    }
    return cb.or(predicates);
}
项目:jpa-spec    文件:NotEqualSpecification.java   
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    From from = getRoot(property, root);
    String field = getProperty(property);
    if (values == null) {
        return cb.isNotNull(from.get(field));
    }
    if (values.length == 1) {
        return getPredicate(from, cb, values[0], field);
    }
    Predicate[] predicates = new Predicate[values.length];
    for (int i = 0; i < values.length; i++) {
        predicates[i] = getPredicate(root, cb, values[i], field);
    }
    return cb.or(predicates);
}
项目: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    文件: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;
}
项目: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);
}
项目:SparkCommerce    文件: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);
    }
}
项目: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);
}
项目:herd    文件:AbstractHerdDao.java   
/**
 * TODO This method may be bdata specific. Consider creating new abstract class to group all bdata related DAO. Builds a query restriction predicate for the
 * specified entities as per business object data key values.
 *
 * @param builder the criteria builder
 * @param businessObjectDataEntity the business object data entity that appears in the from clause
 * @param businessObjectFormatEntity the business object format entity that appears in the from clause
 * @param fileTypeEntity the file type entity that appears in the from clause
 * @param businessObjectDefinitionEntity the business object definition entity that appears in the from clause
 * @param businessObjectDataKey the business object data key
 *
 * @return the query restriction predicate
 */
protected Predicate getQueryRestriction(CriteriaBuilder builder, From<?, BusinessObjectDataEntity> businessObjectDataEntity,
    From<?, BusinessObjectFormatEntity> businessObjectFormatEntity, From<?, FileTypeEntity> fileTypeEntity,
    From<?, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity, BusinessObjectDataKey businessObjectDataKey)
{
    // Create the standard restrictions based on the business object format key values that are part of the business object data key.
    // Please note that we specify not to ignore the business object format version.
    Predicate predicate = getQueryRestriction(builder, businessObjectFormatEntity, fileTypeEntity, businessObjectDefinitionEntity,
        getBusinessObjectFormatKey(businessObjectDataKey), false);

    // Create and append a restriction on partition values.
    predicate = builder.and(predicate, getQueryRestrictionOnPartitionValues(builder, businessObjectDataEntity, businessObjectDataKey));

    // If it is specified, create and append a restriction on business object data version.
    if (businessObjectDataKey.getBusinessObjectDataVersion() != null)
    {
        predicate = builder.and(predicate,
            builder.equal(businessObjectDataEntity.get(BusinessObjectDataEntity_.version), businessObjectDataKey.getBusinessObjectDataVersion()));
    }

    return predicate;
}
项目:herd    文件:AbstractHerdDao.java   
/**
 * TODO This method may be bdata specific. Consider creating new abstract class to group all bdata related DAO. Builds a query restriction predicate for the
 * specified business object data entity as per primary and sub-partition values in the business object data key.
 *
 * @param builder the criteria builder
 * @param businessObjectDataEntity the business object data entity that appears in the from clause
 * @param primaryPartitionValue the primary partition value of the business object data
 * @param subPartitionValues the list of sub-partition values for the business object data
 *
 * @return the query restriction predicate
 */
protected Predicate getQueryRestrictionOnPartitionValues(CriteriaBuilder builder, From<?, BusinessObjectDataEntity> businessObjectDataEntity,
    String primaryPartitionValue, List<String> subPartitionValues)
{
    // Create a standard restriction on primary partition value.
    Predicate predicate = builder.equal(businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue), primaryPartitionValue);

    // Create and add standard restrictions on sub-partition values. Please note that the subpartition value columns are nullable.
    int subPartitionValuesCount = CollectionUtils.size(subPartitionValues);
    for (int i = 0; i < BusinessObjectDataEntity.MAX_SUBPARTITIONS; i++)
    {
        predicate = builder.and(predicate, i < subPartitionValuesCount ?
            builder.equal(businessObjectDataEntity.get(BUSINESS_OBJECT_DATA_SUBPARTITIONS.get(i)), subPartitionValues.get(i)) :
            builder.isNull(businessObjectDataEntity.get(BUSINESS_OBJECT_DATA_SUBPARTITIONS.get(i))));
    }

    return predicate;
}
项目:herd    文件:AbstractHerdDao.java   
/**
 * TODO This method may be bdata specific. Consider creating new abstract class to group all bdata related DAO. Builds a query restriction predicate for the
 * sub-query business object data entity as per partition values from the specified main query business object data entity.
 *
 * @param builder the criteria builder
 * @param businessObjectDataEntity the business object data entity that appears in the from clause
 * @param partitionFilters the list of partition filter to be used to select business object data instances. Each partition filter contains a list of
 * primary and sub-partition values in the right order up to the maximum partition levels allowed by business object data registration - with partition
 * values for the relative partitions not to be used for selection passed as nulls.
 *
 * @return the query restriction predicate
 */
protected Predicate getQueryRestrictionOnPartitionValues(CriteriaBuilder builder, From<?, BusinessObjectDataEntity> businessObjectDataEntity,
    List<List<String>> partitionFilters)
{
    // Create a query restriction as per specified primary and/or sub-partition values.
    Predicate predicate = null;
    for (List<String> partitionFilter : partitionFilters)
    {
        // Add restriction for each partition level if the relative partition value is specified in the partition filter.
        Predicate partitionRestriction = null;
        for (int partitionLevel = 0; partitionLevel < BusinessObjectDataEntity.MAX_SUBPARTITIONS + 1; partitionLevel++)
        {
            String partitionValue = partitionFilter.get(partitionLevel);
            if (StringUtils.isNotBlank(partitionValue))
            {
                Predicate partitionValueRestriction =
                    builder.equal(businessObjectDataEntity.get(BUSINESS_OBJECT_DATA_PARTITIONS.get(partitionLevel)), partitionValue);
                partitionRestriction =
                    (partitionRestriction == null ? partitionValueRestriction : builder.and(partitionRestriction, partitionValueRestriction));
            }
        }
        predicate = (predicate == null ? partitionRestriction : builder.or(predicate, partitionRestriction));
    }

    return predicate;
}
项目:herd    文件:AbstractHerdDao.java   
/**
 * TODO This method may be bdata specific. Consider creating new abstract class to group all bdata related DAO. Builds a query restriction predicate for the
 * sub-query business object data entity as per partition values from the specified main query business object data entity.
 *
 * @param builder the criteria builder
 * @param subBusinessObjectDataEntity the sub-query business object data entity that appears in the from clause
 * @param mainBusinessObjectDataEntity the main query business object data entity that appears in the from clause
 *
 * @return the query restriction predicate
 */
protected Predicate getQueryRestrictionOnPartitionValues(CriteriaBuilder builder, From<?, BusinessObjectDataEntity> subBusinessObjectDataEntity,
    From<?, BusinessObjectDataEntity> mainBusinessObjectDataEntity)
{
    // Create a standard restriction on primary partition value.
    Predicate predicate = builder.equal(subBusinessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue),
        mainBusinessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue));

    // Create and add standard restrictions on sub-partition values. Please note that the subpartition value columns are nullable.
    for (SingularAttribute<BusinessObjectDataEntity, String> businessObjectDataPartitionValueSingularAttribute : BUSINESS_OBJECT_DATA_SUBPARTITIONS)
    {
        predicate = builder.and(predicate, builder.or(builder
            .and(builder.isNull(subBusinessObjectDataEntity.get(businessObjectDataPartitionValueSingularAttribute)),
                builder.isNull(mainBusinessObjectDataEntity.get(businessObjectDataPartitionValueSingularAttribute))), builder
            .equal(subBusinessObjectDataEntity.get(businessObjectDataPartitionValueSingularAttribute),
                mainBusinessObjectDataEntity.get(businessObjectDataPartitionValueSingularAttribute))));
    }

    return predicate;
}
项目:herd    文件:AbstractHerdDao.java   
/**
 * TODO This method may be bdata specific. Consider creating new abstract class to group all bdata related DAO. Builds query restriction predicates and adds
 * them to the query restriction as per specified business object data version and status. If a business object data version is specified, the business
 * object data status is ignored. When both business object data version and business object data status are not specified, the sub-query restriction is not
 * getting updated.
 *
 * @param builder the criteria builder
 * @param businessObjectDataEntity the business object data entity that appears in the from clause
 * @param businessObjectDataStatusEntity the business object data status entity that appears in the from clause
 * @param businessObjectDataVersion the business object data version
 * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified.
 *
 * @return the query restriction predicate or null if both business object data version and business object data status are not specified
 */
protected Predicate getQueryRestrictionOnBusinessObjectDataVersionAndStatus(CriteriaBuilder builder,
    From<?, BusinessObjectDataEntity> businessObjectDataEntity, From<?, BusinessObjectDataStatusEntity> businessObjectDataStatusEntity,
    Integer businessObjectDataVersion, String businessObjectDataStatus)
{
    Predicate predicate = null;

    // If specified, create a standard restriction on the business object data version.
    if (businessObjectDataVersion != null)
    {
        predicate = builder.equal(businessObjectDataEntity.get(BusinessObjectDataEntity_.version), businessObjectDataVersion);
    }
    // Only if a business object data version is not specified, check if we need to add a restriction on the business object data status.
    else if (businessObjectDataStatus != null)
    {
        predicate =
            builder.equal(builder.upper(businessObjectDataStatusEntity.get(BusinessObjectDataStatusEntity_.code)), businessObjectDataStatus.toUpperCase());
    }

    return predicate;
}
项目:spring-data-jpa-datatables    文件:ColumnFilter.java   
@Override
public javax.persistence.criteria.Predicate createPredicate(From<?, ?> from, CriteriaBuilder criteriaBuilder, String attributeName) {
    Expression<?> expression = from.get(attributeName);

    if (values.isEmpty()) {
        return addNullCase ? expression.isNull() : criteriaBuilder.conjunction();
    } else if (isBasicFilter()) {
        return super.createPredicate(from, criteriaBuilder, attributeName);
    }

    javax.persistence.criteria.Predicate predicate;
    if (isBooleanComparison) {
        predicate = expression.in(booleanValues);
    } else {
        predicate = expression.as(String.class).in(values);
    }
    if (addNullCase) predicate = criteriaBuilder.or(predicate, expression.isNull());

    return predicate;
}
项目:blcdemo    文件: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);
    }
}
项目:blcdemo    文件: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;
}
项目:blcdemo    文件: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);
}
项目:blcdemo    文件:ProductCustomPersistenceHandler.java   
@Override
public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao
        dynamicEntityDao, RecordHelper helper) throws ServiceException {
    cto.getNonCountAdditionalFilterMappings().add(new FilterMapping()
            .withDirectFilterValues(new EmptyFilterValues())
            .withRestriction(new Restriction()
                            .withPredicateProvider(new PredicateProvider() {
                                public Predicate buildPredicate(CriteriaBuilder builder,
                                                                FieldPathBuilder fieldPathBuilder, From root,
                                                                String ceilingEntity,
                                                                String fullPropertyName, Path explicitPath,
                                                                List directValues) {
                                    root.fetch("defaultSku", JoinType.LEFT);
                                    root.fetch("defaultCategory", JoinType.LEFT);
                                    return null;
                                }
                            })
            ));
    return helper.getCompatibleModule(OperationType.BASIC).fetch(persistencePackage, cto);
}
项目:FHIR-Server    文件:BaseFhirResourceDao.java   
private Predicate createCompositeParamPart(CriteriaBuilder builder, Root<ResourceTable> from, RuntimeSearchParam left, IQueryParameterType leftValue) {
    Predicate retVal = null;
    switch (left.getParamType()) {
    case STRING: {
        From<ResourceIndexedSearchParamString, ResourceIndexedSearchParamString> stringJoin = from.join("myParamsString", JoinType.INNER);
        retVal = createPredicateString(leftValue, left.getName(), builder, stringJoin);
        break;
    }
    case TOKEN: {
        From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> tokenJoin = from.join("myParamsToken", JoinType.INNER);
        retVal = createPredicateToken(leftValue, left.getName(), builder, tokenJoin);
        break;
    }
    case DATE: {
        From<ResourceIndexedSearchParamDate, ResourceIndexedSearchParamDate> dateJoin = from.join("myParamsDate", JoinType.INNER);
        retVal = createPredicateDate(builder, dateJoin, leftValue);
        break;
    }
    }

    if (retVal == null) {
        throw new InvalidRequestException("Don't know how to handle composite parameter with type of " + left.getParamType());
    }

    return retVal;
}
项目:jpasearch    文件:JpaUtil.java   
@SuppressWarnings("unchecked")
public <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) {
    Path<?> path = root;
    for (Attribute<?, ?> attribute : attributes) {
        boolean found = false;
        if (path instanceof FetchParent) {
            for (Fetch<E, ?> fetch : ((FetchParent<?, E>) path).getFetches()) {
                if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) {
                    path = (Join<E, ?>) fetch;
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            if ((attributes.indexOf(attribute) != (attributes.size() - 1)) && (attribute instanceof Bindable)
                    && Identifiable.class.isAssignableFrom(((Bindable<?>) attribute).getBindableJavaType()) && (path instanceof From)) {
                path = ((From<?, ?>) path).join(attribute.getName(), JoinType.LEFT);
            } else {
                path = path.get(attribute.getName());
            }
        }
    }
    return (Path<F>) path;
}
项目:nemo-utils    文件:BaseJPADAO.java   
/**
 * Constructs a predicate using Java EE's Criteria API depending on the type of criterion.
 * 
 * @param cb
 *          The criteria builder.
 * @param path
 *          The path object (root, join, etc.).
 * @param model
 *          The model object (managed type, entity type, etc.).
 * @param criterion
 *          The criterion used to build the predicate.
 * 
 * @return The predicate object that can be used to compose a CriteriaQuery.
 * @see javax.persistence.criteria.CriteriaQuery
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate createPredicate(CriteriaBuilder cb, From path, ManagedType model, Criterion criterion) {
    // Remove @SupressWarnings and add the correct generic types to all operations.

    // Obtains the final path. This is done in case navigation is required.
    Path finalPath = findPath(path, model, criterion.getFieldName());

    // Check the criterion type.
    switch (criterion.getType()) {
    case IS_NULL:
        return cb.isNull(finalPath);

    case IS_NOT_NULL:
        return cb.isNotNull(finalPath);

    case EQUALS:
        return cb.equal(finalPath, criterion.getParam());

    case LIKE:
        return cb.like(cb.lower(finalPath), "%" + criterion.getParam().toString().toLowerCase() + "%");
    }

    // Thrown an exception in the case of an unknown criterion type.
    throw new IllegalArgumentException("Unknown criterion type: " + this);
}
项目:query-utils    文件:ProjectionHelper.java   
public <E> List<Selection<?>> prepareProjectingQuery(MetaJpaConstructor<E,?,?> projection, From<?,? extends E> selection) {
    logger.debug("prepareProjectingQuery({},{})", projection, selection);

    List<Selection<?>> ret;
    if (projection instanceof IdProjection) {
        logger.debug("IdProjection. Replacing selection {} with just Id.", selection);
        ret = Collections.<Selection<?>>newList(selection.get(QueryUtils.<E,Object>id(selection.getJavaType(), em.apply())));
    } else {
        ret = newListOfSize(projection.getParameters().size());
        for (Tuple3<Integer, Attribute<?,?>, Class<?>> t: zip(range(0), projection.getParameters(), projection.getConstructorParameterTypes())) {
            int index = t._1;
            Attribute<?,?> param = t._2;
            Class<?> constuctorParameterType = t._3;
            ret.add(transformSelectionForQuery(param, isId(constuctorParameterType) || isWrapperOfIds(projection, index), selection, projection));
        }
    }

    logger.debug("prepareProjectingQuery -> {}", ret);
    return ret;
}
项目:query-utils    文件:JpaBasicQueries.java   
@SuppressWarnings("unchecked")
public <E extends IEntity<?> & Identifiable<? extends Id<E>> & Removable> void removeAll(CriteriaQuery<E> query) {
    @SuppressWarnings("unchecked")
    CriteriaQuery<Id<E>> q = (CriteriaQuery<Id<E>>)(Object)em.apply().getCriteriaBuilder().createQuery();
    jpaCriteriaCopy.copyCriteriaWithoutSelect(query, q, em.apply().getCriteriaBuilder());
    From<?,E> selection = resolveSelection(query, q);

    q.multiselect(projectionSupport.prepareProjectingQuery(Project.id(), selection));
    Collection<Id<E>> idList = queryExecutor.getMany(q, Page.NoPaging, LockModeType.NONE);

    Iterable<? extends Iterable<Id<E>>> grouped;
    if (!config.getInClauseValuesAmounts().isEmpty()) {
        grouped = grouped(config.getInClauseValuesAmounts().last(), idList);
    } else {
        grouped = Arrays.asList(idList);
    }
    for (Iterable<Id<E>> ids: grouped) {
        em.apply().createQuery("delete from " + resolveSelection(query).getJavaType().getName() + " e where e.id in (:ids)").setParameter("ids", newList(ids)).executeUpdate();
    }
}
项目:query-utils    文件:JpaCriteriaCopy.java   
/**
 * @return last possibly used alias
 */
private int copyJoins(From<?, ?> from, From<?, ?> to, int counter) {
    for (Join<?, ?> join : sort(comparator, from.getJoins())) {
        Attribute<?, ?> attr = join.getAttribute();
        // Hibern fails with String-bases api; Join.join(String, JoinType)
        @SuppressWarnings({ "rawtypes", "unchecked" })
        Join<Object, Object> j = attr instanceof SingularAttribute ? to.join((SingularAttribute) join.getAttribute(), join.getJoinType()) :
            attr instanceof CollectionAttribute ? to.join((CollectionAttribute) join.getAttribute(), join.getJoinType()) :
            attr instanceof SetAttribute ? to.join((SetAttribute) join.getAttribute(), join.getJoinType()) :
            attr instanceof ListAttribute ? to.join((ListAttribute) join.getAttribute(), join.getJoinType()) :
            attr instanceof MapAttribute ? to.join((MapAttribute) join.getAttribute(), join.getJoinType()) :
            to.join((CollectionAttribute) join.getAttribute(), join.getJoinType());
        copyAlias(join, j, ++counter);
        counter = copyJoins(join, j, ++counter);
    }
    copyFetches(from, to);
    return counter;
}
项目:deltaspike    文件:JoinBuilder.java   
@Override
public List<Predicate> build(CriteriaBuilder builder, Path<P> path)
{
    Join join = null;
    if (singular != null)
    {
        join = joinSingular((From) path);
    }
    else if (list != null)
    {
        join = joinList((From) path);
    }
    else if (collection != null)
    {
        join = joinCollection((From) path);
    }
    else if (set != null)
    {
        join = joinSet((From) path);
    }
    else
    {
        join = joinMap((From) path);
    }
    return criteria.predicates(builder, join);
}
项目:bootstrap    文件:AbstractSpecification.java   
/**
 * Return the ORM path from the given rule.
 * 
 * @param root
 *            root
 * @param path
 *            path
 * @param <U>
 *            The entity type referenced by the {@link Root}
 */
@SuppressWarnings("unchecked")
protected <U, T> Path<T> getOrmPath(final Root<U> root, final String path) {
    PathImplementor<?> currentPath = (PathImplementor<?>) root;
    for (final String pathFragment : path.split(DELIMITERS)) {
        currentPath = getNextPath(pathFragment, (From<?, ?>) currentPath);
    }

    // Fail safe identifier access for non singular target path
    if (currentPath instanceof SingularAttributeJoin) {
        currentPath = getNextPath(((IdentifiableType<?>) currentPath.getModel()).getId(Object.class).getName(), (From<?, ?>) currentPath);
    }
    return (Path<T>) currentPath;
}
项目:bootstrap    文件:AbstractSpecification.java   
@SuppressWarnings("unchecked")
private <X> PathImplementor<X> getNextPath(final String pathFragment, final From<?, ?> from) {
    PathImplementor<?> currentPath = (PathImplementor<?>) from.get(pathFragment);
    fixAlias(from, aliasCounter);

    // Handle join. Does not manage many-to-many
    if (currentPath.getAttribute().getPersistentAttributeType() != PersistentAttributeType.BASIC) {
        currentPath = getJoinPath(from, currentPath.getAttribute());
        if (currentPath == null) {
            // if no join, we create it
            currentPath = fixAlias(from.join(pathFragment, JoinType.LEFT), aliasCounter);
        }
    }
    return (PathImplementor<X>) currentPath;
}
项目:bootstrap    文件:AbstractSpecification.java   
/**
 * Retrieve an existing join within the ones within the given root and that match to given attribute.
 * 
 * @param from
 *            the from source element.
 * @param attribute
 *            the attribute to join
 * @return The join/fetch path if it exists.
 * @param <U>
 *            The source type of the {@link Join}
 */
@SuppressWarnings("unchecked")
protected <U, T> PathImplementor<T> getJoinPath(final From<?, U> from, final Attribute<?, ?> attribute) {

    // Search within current joins
    for (final Join<U, ?> join : from.getJoins()) {
        if (join.getAttribute().equals(attribute)) {
            return fixAlias((Join<U, T>) join, aliasCounter);
        }
    }
    return null;
}
项目:datatable-java    文件:DatatableHelper.java   
/**
 * Cree une expression Criteria API avec l'atribut de l'entité passé en parametre
 * 
 * @param root
 *            entité JPA contenant le champ
 * @param columnData
 *            nom du champ
 * @param clazz
 *            class du champ
 * @param <S>
 *            type du champ
 * @return l'expression de l'atribut
 */
public static <S> Path<S> getExpression(final Root<?> root, final String columnData, final Class<S> clazz) {
    if (!columnData.contains(DatatableSpecification.ATTRIBUTE_SEPARATOR)) {
        // columnData is like "attribute" so nothing particular to do
        return root.get(columnData);
    }
    // columnData is like "joinedEntity.attribute" so add a join clause
    final String[] values = columnData.split(DatatableSpecification.ESCAPED_ATTRIBUTE_SEPARATOR);
    final Attribute<?, ?> attribute = root.getModel().getAttribute(values[0]);
    if (attribute == null) {
        throw new IllegalArgumentException(
            "Colonne '" + values[0] + "' (" + columnData + ") introuvable depuis l'entité '" + root.getJavaType()
                + "'");
    }
    if (attribute.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED) {
        // with @Embedded attribute
        return root.get(values[0]).get(values[1]);
    }
    From<?, ?> from = root;
    for (int i = 0; i < values.length - 1; i++) {

        Join<?, ?> join = null;
        for (final Join<?, ?> joinCandidate : from.getJoins()) {
            if (joinCandidate.getAttribute().getName().equals(values[i])) {
                // LOGGER.debug("Trouve joint d'entite: '{}'", values[i]);
                join = joinCandidate;
            }
        }
        if (join == null) {
            // LOGGER.debug("Joigant entite '{}'...", values[i]);
            join = from.join(values[i], JoinType.INNER);
        }
        from = join;
    }
    return from.get(values[values.length - 1]);
}
项目:oma-riista-web    文件:PublicCalendarEventSearchFeature.java   
private static Predicate getPredicate(
        CriteriaBuilder cb, From<?, Organisation> organisationJoin, OrganisationType orgType, String officialCode) {

    return cb.and(
            cb.equal(organisationJoin.get(Organisation_.organisationType), orgType),
            cb.equal(organisationJoin.get(Organisation_.officialCode), officialCode));
}
项目:oma-riista-web    文件:JpaSubQuery.java   
@Nonnull
public static <P, S> JpaSubQuery<P, S> of(@Nonnull final SingularAttribute<? super P, S> attribute) {
    return new AbstractSubQuery<P, S, SingularAttribute<? super P, S>>(Objects.requireNonNull(attribute)) {
        @Override
        protected From<P, S> join(final Root<P> root) {
            return root.join(attribute);
        }
    };
}
项目:oma-riista-web    文件:JpaSubQuery.java   
@Nonnull
public static <P, S> JpaSubQuery<P, S> of(@Nonnull final PluralAttribute<P, ?, S> attribute) {
    return new AbstractSubQuery<P, S, PluralAttribute<P, ?, S>>(Objects.requireNonNull(attribute)) {
        @Override
        protected From<P, S> join(final Root<P> root) {
            return CriteriaUtils.join(root, attribute);
        }
    };
}
项目:oma-riista-web    文件:JpaPreds.java   
@Nonnull
public static <T extends LifecycleEntity<? extends Serializable>> Predicate notSoftDeleted(
        @Nonnull final CriteriaBuilder cb, @Nonnull final From<?, T> from) {

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

    return cb.isNull(from.get(LifecycleEntity_.lifecycleFields).get(EntityLifecycleFields_.deletionTime));
}
项目:my-paper    文件:BaseDaoImpl.java   
private void copyJoins(From<?, ?> from, From<?, ?> to) {
    for (Join<?, ?> join : from.getJoins()) {
        Join<?, ?> toJoin = to.join(join.getAttribute().getName(), join.getJoinType());
        toJoin.alias(getAlias(join));
        copyJoins(join, toJoin);
    }
    for (Fetch<?, ?> fetch : from.getFetches()) {
        Fetch<?, ?> toFetch = to.fetch(fetch.getAttribute().getName());
        copyFetches(fetch, toFetch);
    }
}
项目:katharsis-framework    文件:JpaCriteriaQueryBackend.java   
@Override
public Expression<?> joinMapValue(Expression<?> currentCriteriaPath, MetaAttribute pathElement, Object key) {
    MapJoin<Object, Object, Object> mapJoin = ((From<?, ?>) currentCriteriaPath).joinMap(pathElement.getName(),
            JoinType.LEFT);
    Predicate mapJoinCondition = cb.equal(mapJoin.key(), key);
    Predicate nullCondition = cb.isNull(mapJoin.key());
    addPredicate(cb.or(mapJoinCondition, nullCondition));
    return mapJoin;
}
项目:katharsis-framework    文件:JpaCriteriaQueryBackend.java   
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Expression<?> getAttribute(Expression<?> currentCriteriaPath, MetaAttribute pathElement) {
    if (pathElement instanceof MetaComputedAttribute) {
        MetaComputedAttribute projAttr = (MetaComputedAttribute) pathElement;
        JpaCriteriaExpressionFactory expressionFactory = (JpaCriteriaExpressionFactory<?>) queryImpl.getComputedAttrs()
                .get(projAttr);

        From from = (From) currentCriteriaPath;
        return expressionFactory.getExpression(from, getCriteriaQuery());
    }
    else {
        return ((Path<?>) currentCriteriaPath).get(pathElement.getName());
    }
}