javax.persistence.criteria.Expression Java Examples

The following examples show how to use javax.persistence.criteria.Expression. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JpaQueryUtils.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
public static void processLessEqualOperator(CriteriaBuilder cb, List<Predicate> predicates, Filter filter, Expression filterExpr) {
    Object value = filter.getValue();
    if (value instanceof Date) {
        Timestamp timestamp = new Timestamp(((Date) value).getTime());
        predicates.add(cb.lessThanOrEqualTo(filterExpr, timestamp));
    } else if (value instanceof String) {
        if (filterExpr.getJavaType().equals(Timestamp.class)) {
            java.util.Date date = DateUtils.convertToTimestamp(String.valueOf(value));
            predicates.add(cb.lessThanOrEqualTo(filterExpr, new Timestamp(date.getTime())));
        } else {
            predicates.add(cb.lessThanOrEqualTo(filterExpr, (String) value));
        }
    } else if (value instanceof Number) {
        if (value instanceof Integer)
            predicates.add(cb.lessThanOrEqualTo(filterExpr, (Integer) value));
        if (value instanceof Long)
            predicates.add(cb.lessThanOrEqualTo(filterExpr, (Long) value));
        if (value instanceof Float)
            predicates.add(cb.lessThanOrEqualTo(filterExpr, (Float) value));
        if (value instanceof Double)
            predicates.add(cb.lessThanOrEqualTo(filterExpr, (Double) value));
    }
}
 
Example #2
Source File: CriteriaBuilderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Predicate isTrue(Expression<Boolean> expression) {
	if ( CompoundPredicate.class.isInstance( expression ) ) {
		final CompoundPredicate predicate = (CompoundPredicate) expression;
		if ( predicate.getExpressions().size() == 0 ) {
			return new BooleanStaticAssertionPredicate(
					this,
					predicate.getOperator() == Predicate.BooleanOperator.AND
			);
		}
		return predicate;
	}
	else if ( Predicate.class.isInstance( expression ) ) {
		return (Predicate) expression;
	}
	return new BooleanAssertionPredicate( this, expression, Boolean.TRUE );
}
 
Example #3
Source File: BuildRecordPredicates.java    From pnc with Apache License 2.0 6 votes vote down vote up
public static Predicate<BuildRecord> withBuildConfigurationIdRev(List<IdRev> buildConfigurationsWithIdRevs) {
    if (buildConfigurationsWithIdRevs.isEmpty()) {
        return Predicate.nonMatching();
    }

    List<String> idRevs = buildConfigurationsWithIdRevs.stream()
            .map(idRev -> idRev.getId() + "-" + idRev.getRev())
            .collect(Collectors.toList());

    return (root, query, cb) -> {
        Expression<String> concat = cb.concat(root.get(BuildRecord_.buildConfigurationId).as(String.class), "-");
        Expression<String> buildRecordIdRev = cb
                .concat(concat, root.get(BuildRecord_.buildConfigurationRev).as(String.class));
        logger.debug("Searching for BuildRecords with {}", idRevs);
        return buildRecordIdRev.in(idRevs);
    };
}
 
Example #4
Source File: RSQLUtilityTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void correctRsqlBuildsLessThanPredicate() {
    reset(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
    final String correctRsql = "name=lt=abc";
    when(baseSoftwareModuleRootMock.get("name")).thenReturn(baseSoftwareModuleRootMock);
    when(baseSoftwareModuleRootMock.getJavaType()).thenReturn((Class) SoftwareModule.class);
    when(criteriaBuilderMock.lessThan(any(Expression.class), anyString())).thenReturn(mock(Predicate.class));
    when(criteriaBuilderMock.<String> greaterThanOrEqualTo(any(Expression.class), any(String.class)))
            .thenReturn(mock(Predicate.class));
    // test
    RSQLUtility.parse(correctRsql, SoftwareModuleFields.class, null, testDb).toPredicate(baseSoftwareModuleRootMock,
            criteriaQueryMock, criteriaBuilderMock);

    // verification
    verify(criteriaBuilderMock, times(1)).and(any(Predicate.class));
    verify(criteriaBuilderMock, times(1)).lessThan(eq(pathOfString(baseSoftwareModuleRootMock)), eq("abc"));
}
 
Example #5
Source File: CiServiceImpl.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> convertResponse(List<Expression> selections, Object[] response, List<FieldInfo> fieldInfos) {
    if (selections.size() > fieldInfos.size()) {
        throw new ServiceException("Selections size should not be larger than field infor size.");
    }
    
    Map<Expression,Integer> exprIndexMap = new HashMap<>();
    for(int i=0;i<selections.size();i++) {
    	exprIndexMap.put(selections.get(i), i);
    }

    Map<String, Object> rowMap = new HashMap<>();
    
    for(FieldInfo fieldInfo:fieldInfos) {
    	Expression expr = fieldInfo.getExpression();
        AdmCiTypeAttr attr = null;
        if (fieldInfo.getAttrId() != null) {
            attr = ciTypeAttrRepository.getOne(fieldInfo.getAttrId());
        }
        Object convertedObj = convertFieldValue(expr.getAlias(), response[exprIndexMap.get(expr)], attr);
        rowMap.put(fieldInfo.getAlias(), convertedObj);
    }
    
    return rowMap;
}
 
Example #6
Source File: CiServiceImpl.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
private void extractGuidKvPair(Map<String, Map<String, Expression>> guidRguidPair, Map.Entry<String, Expression> kv, String postFix) {
    if (kv.getKey().endsWith(postFix)) {
        String keyPrefix = kv.getKey().substring(0, kv.getKey().indexOf(postFix));
        if (guidRguidPair.get(keyPrefix) == null) {
            Map<String, Expression> keyMap = new HashMap<>();
            guidRguidPair.put(keyPrefix, keyMap);
        }
        guidRguidPair.get(keyPrefix).put(postFix, kv.getValue());
    }
}
 
Example #7
Source File: JpaQueryUtils.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
private static Expression validateFilterName(Map<String, Expression> selectionMap, Filter filter) {
    Expression filterExpr = selectionMap.get(filter.getName());
    if (filterExpr == null) {
        throw new InvalidArgumentException(String.format("Given filter name [%s] is not existed.", filter.getName()));
    }
    return filterExpr;
}
 
Example #8
Source File: OperationQueryImpl.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public OperationQuery withStateAnyOf(List<Operation.State> states) {
    queryCriteria.addRestriction(ImmutableQueryAttributeRestriction.<List<Operation.State>> builder()
                                                                   .attribute(AttributeNames.FINAL_STATE)
                                                                   .condition(Expression::in)
                                                                   .value(states)
                                                                   .build());
    return this;
}
 
Example #9
Source File: JpaCriteriaQueryBackend.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public JpaCriteriaQueryBackend(JpaCriteriaQueryImpl<T> query, EntityManager em, Class<T> clazz, MetaDataObject parentMeta,
                               MetaAttribute parentAttr, String parentKey, boolean parentIdSelection) {
    this.queryImpl = query;
    this.parentKey = parentKey;

    cb = em.getCriteriaBuilder();
    criteriaQuery = (CriteriaQuery<T>) cb.createQuery();

    if (parentMeta != null) {
        parentFrom = criteriaQuery.from(parentMeta.getImplementationClass());
        root = parentFrom.join(parentAttr.getName());
        joinHelper = new JoinRegistry<>(this, query);
        joinHelper.putJoin(new MetaAttributePath(), root);

        if (parentIdSelection) {
            Expression<?> parentIdExpr = getParentIdExpression(parentAttr, parentKey);
            criteriaQuery.multiselect((List) Arrays.asList(parentIdExpr, root));
        } else {
            criteriaQuery.select(root);
        }
    } else {
        root = criteriaQuery.from(clazz);
        joinHelper = new JoinRegistry<>(this, query);
        joinHelper.putJoin(new MetaAttributePath(), root);
        criteriaQuery.select(root);
    }
}
 
Example #10
Source File: LinImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public T notLike(Expression<String> x, Expression<String> pattern) {
	if (!beforeMethodInvoke()) {
		return (T) this;
	}
	add(cb.notLike(x, pattern));
	return (T) this;
}
 
Example #11
Source File: ServiceFacade.java    From aws-photosharing-example with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Predicate getFilterPredicate(Function<Predicate[], Predicate>  p_method, Root<T> p_root, CriteriaBuilder p_builder, Filter[] p_filter) {
	 
	 Predicate predicate = null;
	 
	 if (p_filter != null && p_filter.length > 0) {	
			Path<?> property_path = null;							
			LinkedList<Predicate> predicates = new LinkedList<Predicate>();				
			
			for (Filter filter: p_filter) {							
				for (String hop : filter.getPropertyPath()) {
					if (property_path == null)
						property_path = p_root.get(hop);
					else
						property_path = property_path.get(hop);
				}
				if (filter.getValue() != null) {
					if (filter.isExact())
						predicates.add(p_builder.equal(property_path, filter.getValue()));
					else
						predicates.add(p_builder.like((Expression<String>) property_path, filter.getValue()+"%"));
				} else {
					if (filter.isInverse())
						predicates.add(p_builder.isNotNull(property_path));
					else
						predicates.add(p_builder.isNull(property_path));
				}
				
				property_path = null;					
			}											
			
			if (predicates.size() > 1)
				predicate = p_method.apply(predicates.toArray(new Predicate[predicates.size()]));
			else
				predicate = predicates.get(0);							
	}				 
	return predicate;
 }
 
Example #12
Source File: PredicateUtils.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Create either an equals or like predicate based on the presence of the '%' character in the search value.
 *
 * @param cb         The criteria builder to use for predicate creation
 * @param expression The expression of the field the predicate is acting on
 * @param value      The value to compare the field to
 * @return A LIKE predicate if the value contains a '%' otherwise an EQUAL predicate
 */
static Predicate getStringLikeOrEqualPredicate(
    @NotNull final CriteriaBuilder cb,
    @NotNull final Expression<String> expression,
    @NotNull final String value
) {
    if (StringUtils.contains(value, PERCENT)) {
        return cb.like(expression, value);
    } else {
        return cb.equal(expression, value);
    }
}
 
Example #13
Source File: LinuImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public <Y> Linu set(SingularAttribute<? super Object, Y> attribute, Expression<? extends Y> value) {
	if (!beforeMethodInvoke()) {
		return this;
	}
	criteria.set(attribute, value);
	return this;
}
 
Example #14
Source File: LinImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public T notEqual(Expression<?> x, Expression<?> y) {
	if (!beforeMethodInvoke()) {
		return (T) this;
	}
	add(cb.notEqual(x, y));
	return (T) this;
}
 
Example #15
Source File: AbstractPathImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public <K, V, M extends Map<K, V>> Expression<M> get(MapAttribute<X, K, V> attribute) {
	if ( ! canBeDereferenced() ) {
		throw illegalDereference();
	}

	PluralAttributePath path = (PluralAttributePath) resolveCachedAttributePath( attribute.getName() );
	if ( path == null ) {
		path = new PluralAttributePath( criteriaBuilder(), this, attribute );
		registerAttributePath( attribute.getName(), path );
	}
	return path;
}
 
Example #16
Source File: JpaCriteriaQueryBackend.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Order newSort(Expression<?> expr, Direction dir) {
	if (dir == Direction.ASC) {
		return cb.asc(expr);
	}
	else {
		return cb.desc(expr);
	}
}
 
Example #17
Source File: LinImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public <Y extends Number> T lt(Expression<? extends Y> x, Y y) {
	if (!beforeMethodInvoke()) {
		return (T) this;
	}
	add(cb.lt(x, y));
	return (T) this;
}
 
Example #18
Source File: InPredicate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs an <tt>IN</tt> predicate against a given expression with the given list of expression values.
 *
 * @param criteriaBuilder The query builder from which this originates.
 * @param expression The expression.
 * @param values The value list.
 */
public InPredicate(
		CriteriaBuilderImpl criteriaBuilder,
		Expression<? extends T> expression,
		List<Expression<? extends T>> values) {
	super( criteriaBuilder );
	this.expression = expression;
	this.values = values;
}
 
Example #19
Source File: BusinessObjectDataDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public Long getBusinessObjectDataCount(BusinessObjectFormatKey businessObjectFormatKey)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = builder.createQuery(Long.class);

    // The criteria root is the business object data.
    Root<BusinessObjectDataEntity> businessObjectDataEntity = criteria.from(BusinessObjectDataEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity =
        businessObjectDataEntity.join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity.join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity =
        businessObjectFormatEntity.join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity.join(BusinessObjectDefinitionEntity_.namespace);

    // Create path.
    Expression<Long> businessObjectDataCount = builder.count(businessObjectDataEntity.get(BusinessObjectDataEntity_.id));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction =
        builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), businessObjectFormatKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
        businessObjectFormatKey.getBusinessObjectDefinitionName().toUpperCase()));
    queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)),
        businessObjectFormatKey.getBusinessObjectFormatUsage().toUpperCase()));
    queryRestriction = builder.and(queryRestriction,
        builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)), businessObjectFormatKey.getBusinessObjectFormatFileType().toUpperCase()));
    queryRestriction = builder.and(queryRestriction, builder.equal(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion),
        businessObjectFormatKey.getBusinessObjectFormatVersion()));

    criteria.select(businessObjectDataCount).where(queryRestriction);

    return entityManager.createQuery(criteria).getSingleResult();
}
 
Example #20
Source File: MemberOfPredicate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public MemberOfPredicate(
		CriteriaBuilderImpl criteriaBuilder,
		Expression<E> elementExpression,
		PluralAttributePath<C> collectionPath) {
	super( criteriaBuilder );
	this.elementExpression = elementExpression;
	this.collectionPath = collectionPath;
}
 
Example #21
Source File: JpaQueryUtils.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
public static void processNotEqualsOperator(CriteriaBuilder cb, List<Predicate> predicates, Filter filter,
                                            Expression filterExpr) {

    Object value = filter.getValue();
    if (value instanceof String) {
        if (filterExpr.getJavaType().equals(Timestamp.class)) {
            java.util.Date date = DateUtils.convertToTimestamp((String) value);
            predicates.add(cb.notEqual(filterExpr, new Timestamp(date.getTime())));
        } else {
            predicates.add(cb.notEqual(cb.upper(filterExpr), (String) filter.getValue().toString().toUpperCase()));
        }
    } else {
        predicates.add(cb.notEqual(filterExpr, value));
    }
}
 
Example #22
Source File: LinImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public <Y extends Comparable<? super Y>> T between(Expression<Y> v, String x, String y) {
	if (!beforeMethodInvoke()) {
		return (T) this;
	}
	Expression<Y> xe = root.get(x);
	Expression<Y> ye = root.get(y);
	add(cb.between(v, xe, ye));
	return (T) this;
}
 
Example #23
Source File: LinImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public T in(String property, Expression<?> ...values) {
	if (!beforeMethodInvoke()) {
		return (T) this;
	}
	Expression<?> e = root.get(property);
	add(e.in(values));
	return (T) this;
}
 
Example #24
Source File: CriteriaSubqueryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Expression<T> getSelection() {
	if ( wrappedSelection == null ) {
		if ( queryStructure.getSelection() == null ) {
			return null;
		}
		wrappedSelection = new SubquerySelection<T>( (ExpressionImpl<T>) queryStructure.getSelection(), this );
	}
	return wrappedSelection;
}
 
Example #25
Source File: JpaQueryUtils.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
private static Expression validateFilterName(Map<String, Expression> selectionMap, Filter filter) {
    Expression filterExpr = selectionMap.get(filter.getName());
    if (filterExpr == null) {
        throw new WecubeCoreException(
                String.format("Given filter name [%s] is not existed.", filter.getName()));
    }
    return filterExpr;
}
 
Example #26
Source File: ContestHibernateDao.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
static CustomPredicateFilter<ContestModel> isActive(Clock clock) {
    return (cb, cq, root) -> {
        long currentInstantEpoch = clock.instant().toEpochMilli();
        Expression<Long> beginTime = cb.prod(
                cb.function("unix_timestamp", Double.class, root.get(ContestModel_.beginTime)),
                cb.literal(1000.0)).as(Long.class);
        Expression<Long> endTime = cb.sum(beginTime, root.get(ContestModel_.duration));

        return cb.greaterThanOrEqualTo(endTime, cb.literal(currentInstantEpoch));
    };
}
 
Example #27
Source File: LinImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public <Y extends Comparable<? super Y>> T between(String v, Y x, Y y) {
	if (!beforeMethodInvoke()) {
		return (T) this;
	}
	Expression<Y> ve = root.get(v);
	add(cb.between(ve, x, y));
	return (T) this;
}
 
Example #28
Source File: LinImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public <E> T in(Expression<E> expression, Expression<?> ...values) {
	if (!beforeMethodInvoke()) {
		return (T) this;
	}
	add(expression.in(values));
	return (T) this;
}
 
Example #29
Source File: StaticEntityRepositoryImpl.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
private static void processEqualsOperator(CriteriaBuilder cb, List<Predicate> predicates, String filed, Object value, Path path) {
    Expression filterExpr = path.get(filed);
    if (value instanceof String) {
        predicates.add(cb.equal(cb.upper(filterExpr), (String) value.toString().toUpperCase()));
    } else {
        predicates.add(cb.equal(filterExpr, value));
    }

}
 
Example #30
Source File: JpaQueryUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Generate a String comparison Predicate base on input parameters.
 *
 * Example: JpaUtils.stringPredicate( builder, root.get( "name" ), "%" + key + "%", JpaUtils.StringSearchMode.LIKE, false ) )
 *
 * @param builder CriteriaBuilder
 * @param expressionPath Property Path for query
 * @param objectValue Value to check
 * @param searchMode JpaQueryUtils.StringSearchMode
 * @param caseSesnitive is case sensitive
 * @return a {@link Predicate}.
 */
private static Predicate stringPredicate( CriteriaBuilder builder,
    Expression<String> expressionPath, Object objectValue, StringSearchMode searchMode, boolean caseSesnitive )
{
    Expression<String> path = expressionPath;
    Object attrValue = objectValue;

    if ( !caseSesnitive )
    {
        path = builder.lower( path );
        attrValue = ((String) attrValue).toLowerCase( LocaleContextHolder.getLocale() );
    }

    switch ( searchMode )
    {
        case EQUALS:
            return builder.equal( path, attrValue );
        case ENDING_LIKE:
            return builder.like( path, "%" + attrValue );
        case STARTING_LIKE:
            return builder.like( path, attrValue + "%" );
        case ANYWHERE:
            return builder.like( path, "%" + attrValue + "%" );
        case LIKE:
            return builder.like( path, (String) attrValue ); // assume user provide the wild cards
        default:
            throw new IllegalStateException( "expecting a search mode!" );
    }
}