com.querydsl.core.types.Expression Java Examples

The following examples show how to use com.querydsl.core.types.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: BaseService.java    From ZTuoExchange_framework with MIT License 7 votes vote down vote up
/**
 * @param expressions        查询列表
 * @param entityPaths        查询表
 * @param predicates         条件
 * @param orderSpecifierList 排序
 * @param pageNo             页码
 * @param pageSize           页面大小
 */
@Transactional(readOnly = true)
public PageListMapResult queryDslForPageListResult(
        List<Expression> expressions,
        List<EntityPath> entityPaths,
        List<Predicate> predicates,
        List<OrderSpecifier> orderSpecifierList,
        Integer pageNo,
        Integer pageSize) {
    JPAQuery<Tuple> jpaQuery = queryFactory.select(expressions.toArray(new Expression[expressions.size()]))
            .from(entityPaths.toArray(new EntityPath[entityPaths.size()]))
            .where(predicates.toArray(new Predicate[predicates.size()]));
    List<Tuple> tuples = jpaQuery.orderBy(orderSpecifierList.toArray(new OrderSpecifier[orderSpecifierList.size()]))
            .offset((pageNo - 1) * pageSize).limit(pageSize)
            .fetch();
    List<Map<String, Object>> list = new LinkedList<>();//返回结果
    //封装结果
    for (int i = 0; i < tuples.size(); i++) {
        //遍历tuples
        Map<String, Object> map = new LinkedHashMap<>();//一条信息
        for (Expression expression : expressions) {
            map.put(expression.toString().split(" as ")[1],//别名作为Key
                    tuples.get(i).get(expression));//获取结果
        }
        list.add(map);
    }
    PageListMapResult pageListMapResult = new PageListMapResult(list, pageNo, pageSize, jpaQuery.fetchCount());//分页封装
    return pageListMapResult;
}
 
Example #2
Source File: KeyValueQuerydslUtils.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link Expression} for the given {@link Order} property.
 *
 * @param order must not be {@literal null}.
 * @param builder must not be {@literal null}.
 * @return
 */
private static Expression<?> buildOrderPropertyPathFrom(Order order, PathBuilder<?> builder) {

	Assert.notNull(order, "Order must not be null!");
	Assert.notNull(builder, "Builder must not be null!");

	PropertyPath path = PropertyPath.from(order.getProperty(), builder.getType());
	Expression<?> sortPropertyExpression = builder;

	while (path != null) {

		if (!path.hasNext() && order.isIgnoreCase()) {
			// if order is ignore-case we have to treat the last path segment as a String.
			sortPropertyExpression = Expressions.stringPath((Path<?>) sortPropertyExpression, path.getSegment()).lower();
		} else {
			sortPropertyExpression = Expressions.path(path.getType(), (Path<?>) sortPropertyExpression, path.getSegment());
		}

		path = path.next();
	}

	return sortPropertyExpression;
}
 
Example #3
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Expression<?> doJoin(MetaAttribute targetAttr, JoinType joinType, Expression<?> parent) {
	if (targetAttr instanceof MetaComputedAttribute) {

		MetaComputedAttribute computedAttr = (MetaComputedAttribute) targetAttr;
		QuerydslExpressionFactory expressionFactory = (QuerydslExpressionFactory<?>) queryImpl.getComputedAttrs()
				.get(computedAttr);

		return expressionFactory.getExpression(parent, getQuery());
	}
	else {
		Expression<Object> expression = QuerydslUtils.get(parent, targetAttr.getName());
		querydslQuery.getMetadata().addJoin(QuerydslUtils.convertJoinType(joinType), expression);
		return expression;
	}
}
 
Example #4
Source File: BaseService.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
@Transactional(readOnly = true)
public PageListMapResult queryDslForPageListResult(QueryDslContext qdc, Integer pageNo, Integer pageSize) {
    JPAQuery<Tuple> jpaQuery = queryFactory.select(qdc.expressionToArray())
            .from(qdc.entityPathToArray())
            .where(qdc.predicatesToArray());
    List<Tuple> tuples = jpaQuery.orderBy(qdc.orderSpecifiersToArray())
            .offset((pageNo - 1) * pageSize).limit(pageSize)
            .fetch();
    List<Map<String, Object>> list = new LinkedList<>();//返回结果
    //封装结果
    for (int i = 0; i < tuples.size(); i++) {
        //遍历tuples
        Map<String, Object> map = new LinkedHashMap<>();//一条信息
        for (Expression expression : qdc.getExpressions()) {
            map.put(expression.toString().split(" as ")[1],//别名作为Key
                    tuples.get(i).get(expression));//获取结果
        }
        list.add(map);
    }
    PageListMapResult pageListMapResult = new PageListMapResult(list, pageNo, pageSize, jpaQuery.fetchCount());//分页封装
    return pageListMapResult;
}
 
Example #5
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Expression<?> doJoin(MetaAttribute targetAttr, JoinType joinType, Expression<?> parent) {
	if (targetAttr instanceof MetaComputedAttribute) {

		MetaComputedAttribute computedAttr = (MetaComputedAttribute) targetAttr;
		QuerydslExpressionFactory expressionFactory = (QuerydslExpressionFactory<?>) queryImpl.getComputedAttrs()
				.get(computedAttr);

		return expressionFactory.getExpression(parent, getQuery());
	}
	else {
		Expression<Object> expression = QuerydslUtils.get(parent, targetAttr.getName());
		querydslQuery.getMetadata().addJoin(QuerydslUtils.convertJoinType(joinType), expression);
		return expression;
	}
}
 
Example #6
Source File: BaseService.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
@Transactional(readOnly = true)
public PageListMapResult queryDslForPageListResult(QueryDslContext qdc, Integer pageNo, Integer pageSize) {
    JPAQuery<Tuple> jpaQuery = queryFactory.select(qdc.expressionToArray())
            .from(qdc.entityPathToArray())
            .where(qdc.predicatesToArray());
    List<Tuple> tuples = jpaQuery.orderBy(qdc.orderSpecifiersToArray())
            .offset((pageNo - 1) * pageSize).limit(pageSize)
            .fetch();
    List<Map<String, Object>> list = new LinkedList<>();//返回结果
    //封装结果
    for (int i = 0; i < tuples.size(); i++) {
        //遍历tuples
        Map<String, Object> map = new LinkedHashMap<>();//一条信息
        for (Expression expression : qdc.getExpressions()) {
            map.put(expression.toString().split(" as ")[1],//别名作为Key
                    tuples.get(i).get(expression));//获取结果
        }
        list.add(map);
    }
    PageListMapResult pageListMapResult = new PageListMapResult(list, pageNo, pageSize, jpaQuery.fetchCount());//分页封装
    return pageListMapResult;
}
 
Example #7
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
public QuerydslQueryBackend(QuerydslQueryImpl<T> queryImpl, Class<T> clazz, MetaDataObject parentMeta,
		MetaAttribute parentAttr, boolean addParentSelection) {
	this.queryImpl = queryImpl;

	JPAQueryFactory queryFactory = queryImpl.getQueryFactory();

	if (parentMeta != null) {
		parentFrom = QuerydslUtils.getEntityPath(parentMeta.getImplementationClass());
		root = QuerydslUtils.getEntityPath(clazz);

		Path joinPath = (Path) QuerydslUtils.get(parentFrom, parentAttr.getName());
		joinHelper = new JoinRegistry<>(this, queryImpl);

		joinHelper.putJoin(new MetaAttributePath(), root);

		if (addParentSelection) {
			Expression<Object> parentIdExpr = getParentIdExpression(parentMeta, parentAttr);
			querydslQuery = queryFactory.select(parentIdExpr, root);
		}
		else {
			querydslQuery = queryFactory.select(root);
		}

		querydslQuery = querydslQuery.from(parentFrom);
		if (joinPath instanceof CollectionExpression) {
			querydslQuery = querydslQuery.join((CollectionExpression) joinPath, root);
		}
		else {
			querydslQuery = querydslQuery.join((EntityPath) joinPath, root);
		}
	}
	else {
		root = QuerydslUtils.getEntityPath(clazz);
		joinHelper = new JoinRegistry<>(this, queryImpl);
		joinHelper.putJoin(new MetaAttributePath(), root);
		querydslQuery = queryFactory.select(root);
		querydslQuery = querydslQuery.from((EntityPath) root);
	}
}
 
Example #8
Source File: QuerydslUtils.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Expression<T> get(Expression<?> path, String name) {
	try {
		Class<?> clazz = path.getClass();
		Field field = clazz.getField(name);
		return (Expression<T>) field.get(path);
	} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
		throw new IllegalStateException("failed get field " + path + "." + name, e);
	}
}
 
Example #9
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private Expression<Object> getParentIdExpression(MetaDataObject parentMeta, MetaAttribute parentAttr) {
	MetaKey primaryKey = parentMeta.getPrimaryKey();
	PreconditionUtil.verify(primaryKey != null, "no primary key specified for parentAttribute %s", parentAttr.getId());
	List<MetaAttribute> elements = primaryKey.getElements();
	PreconditionUtil.verifyEquals(1, elements.size(), "composite primary keys for %s not supported yet",
			parentMeta.getImplementationClass());
	MetaAttribute primaryKeyAttr = elements.get(0);
	return QuerydslUtils.get(parentFrom, primaryKeyAttr.getName());
}
 
Example #10
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Expression<?> getAttribute(final Expression<?> expression, MetaAttribute pathElement) {
	if (pathElement instanceof MetaComputedAttribute) {
		ComputedAttributeRegistryImpl virtualAttrs = queryImpl.getComputedAttrs();
		QuerydslExpressionFactory expressionFactory = (QuerydslExpressionFactory) virtualAttrs
				.get((MetaComputedAttribute) pathElement);
		return expressionFactory.getExpression(expression, getQuery());
	}
	else {
		return QuerydslUtils.get(expression, pathElement.getName());
	}
}
 
Example #11
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> getJavaElementType(Expression<?> expression) {
	if (expression instanceof CollectionExpressionBase) {
		return ((CollectionExpressionBase) expression).getElementType();
	}
	return expression.getType();
}
 
Example #12
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Override
public OrderSpecifier<?> newSort(Expression<?> expr, Direction dir) {
	if (dir == Direction.ASC) {
		return new OrderSpecifier(Order.ASC, expr);
	}
	else {
		return new OrderSpecifier(Order.DESC, expr);
	}
}
 
Example #13
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Override
public OrderSpecifier<?> newSort(Expression<?> expr, Direction dir) {
	if (dir == Direction.ASC) {
		return new OrderSpecifier(Order.ASC, expr);
	}
	else {
		return new OrderSpecifier(Order.DESC, expr);
	}
}
 
Example #14
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
private Expression<?> handleConversions(Expression<?> expression, FilterOperator operator) {
	// convert to String for LIKE operators
	if (expression.getType() != String.class && (operator == FilterOperator.LIKE)) {
		return ((LiteralExpression) expression).stringValue();
	}
	else {
		return expression;
	}
}
 
Example #15
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Expression<?> getAttribute(final Expression<?> expression, MetaAttribute pathElement) {
	if (pathElement instanceof MetaComputedAttribute) {
		ComputedAttributeRegistryImpl virtualAttrs = queryImpl.getComputedAttrs();
		QuerydslExpressionFactory expressionFactory = (QuerydslExpressionFactory) virtualAttrs
				.get((MetaComputedAttribute) pathElement);
		return expressionFactory.getExpression(expression, getQuery());
	}
	else {
		return QuerydslUtils.get(expression, pathElement.getName());
	}
}
 
Example #16
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private Expression<?> handleConversions(Expression<?> expression, FilterOperator operator) {
	// convert to String for LIKE operators
	if (expression.getType() != String.class && (operator == FilterOperator.LIKE)) {
		return Expressions.stringOperation(Ops.STRING_CAST, expression);
	}
	else {
		return expression;
	}
}
 
Example #17
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> getJavaElementType(Expression<?> expression) {
	if (expression instanceof CollectionExpressionBase) {
		return ((CollectionExpressionBase) expression).getElementType();
	}
	return expression.getType();
}
 
Example #18
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
private Expression<Object> getParentIdExpression(MetaDataObject parentMeta, MetaAttribute parentAttr) {
	MetaKey primaryKey = parentMeta.getPrimaryKey();
	if(primaryKey == null){
		throw new IllegalStateException("no primary key specified for parentAttribute " + parentAttr.getId());
	}
	List<MetaAttribute> elements = primaryKey.getElements();
	PreconditionUtil.assertEquals("composite primary keys not supported yet", 1, elements.size());
	MetaAttribute primaryKeyAttr = elements.get(0);
	return QuerydslUtils.get(parentFrom, primaryKeyAttr.getName());
}
 
Example #19
Source File: TupleUtils.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * @param tuples      查询结果
 * @param expressions 查询字段
 * @return
 */
public static List<Map<String, Object>> tupleToMap(List<Tuple> tuples, List<Expression> expressions) {
    List<Map<String, Object>> list = new LinkedList<>();//返回结果
    //封装结果
    for (int i = 0; i < tuples.size(); i++) {
        //遍历tuples
        Map<String, Object> map = new LinkedHashMap<>();//一条信息
        for (Expression expression : expressions) {
            map.put(expression.toString().split(" as ")[1],//别名作为Key
                    tuples.get(i).get(expression));//获取结果
        }
        list.add(map);
    }
    return list;
}
 
Example #20
Source File: QueryDslTupleImplTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {

	expression = Mockito.mock(Expression.class);
	Tuple tuple = Mockito.mock(Tuple.class);
	Mockito.when(tuple.size()).thenReturn(2);
	Mockito.when(tuple.get(expression)).thenReturn("test");
	Mockito.when(tuple.toArray()).thenReturn(new Object[]{"0", "1"});
	Mockito.when(tuple.get(0, String.class)).thenReturn("0");
	Mockito.when(tuple.get(1, String.class)).thenReturn("1");

	Mockito.when(tuple.size()).thenReturn(2);
	Map<String, Integer> selectionBindings = new HashMap<>();
	impl = new QuerydslTupleImpl(tuple, selectionBindings);
}
 
Example #21
Source File: ComputedAttributeQuerydslTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Override
protected JpaQueryFactory createQueryFactory(EntityManager em) {
	QuerydslQueryFactory factory = QuerydslQueryFactory.newInstance();

	factory.registerComputedAttribute(TestEntity.class, ATTR_VIRTUAL_VALUE, String.class,
			new QuerydslExpressionFactory<QTestEntity>() {

				@Override
				public Expression<?> getExpression(QTestEntity test, JPAQuery<?> query) {
					return test.stringValue.toUpperCase();
				}
			});

	return factory;
}
 
Example #22
Source File: TupleUtils.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * @param tuples      查询结果
 * @param expressions 查询字段
 * @return
 */
public static List<Map<String, Object>> tupleToMap(List<Tuple> tuples, List<Expression> expressions) {
    List<Map<String, Object>> list = new LinkedList<>();//返回结果
    //封装结果
    for (int i = 0; i < tuples.size(); i++) {
        //遍历tuples
        Map<String, Object> map = new LinkedHashMap<>();//一条信息
        for (Expression expression : expressions) {
            map.put(expression.toString().split(" as ")[1],//别名作为Key
                    tuples.get(i).get(expression));//获取结果
        }
        list.add(map);
    }
    return list;
}
 
Example #23
Source File: BaseService.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * @param expressions        查询列表
 * @param entityPaths        查询表
 * @param predicates         条件
 * @param orderSpecifierList 排序
 * @param pageNo             页码
 * @param pageSize           页面大小
 */
@Transactional(readOnly = true)
public PageListMapResult queryDslForPageListResult(
        List<Expression> expressions,
        List<EntityPath> entityPaths,
        List<Predicate> predicates,
        List<OrderSpecifier> orderSpecifierList,
        Integer pageNo,
        Integer pageSize) {
    JPAQuery<Tuple> jpaQuery = queryFactory.select(expressions.toArray(new Expression[expressions.size()]))
            .from(entityPaths.toArray(new EntityPath[entityPaths.size()]))
            .where(predicates.toArray(new Predicate[predicates.size()]));
    List<Tuple> tuples = jpaQuery.orderBy(orderSpecifierList.toArray(new OrderSpecifier[orderSpecifierList.size()]))
            .offset((pageNo - 1) * pageSize).limit(pageSize)
            .fetch();
    List<Map<String, Object>> list = new LinkedList<>();//返回结果
    //封装结果
    for (int i = 0; i < tuples.size(); i++) {
        //遍历tuples
        Map<String, Object> map = new LinkedHashMap<>();//一条信息
        for (Expression expression : expressions) {
            map.put(expression.toString().split(" as ")[1],//别名作为Key
                    tuples.get(i).get(expression));//获取结果
        }
        list.add(map);
    }
    PageListMapResult pageListMapResult = new PageListMapResult(list, pageNo, pageSize, jpaQuery.fetchCount());//分页封装
    return pageListMapResult;
}
 
Example #24
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
public QuerydslQueryBackend(QuerydslQueryImpl<T> queryImpl, Class<T> clazz, MetaDataObject parentMeta,
		MetaAttribute parentAttr, boolean addParentSelection) {
	this.queryImpl = queryImpl;

	JPAQueryFactory queryFactory = queryImpl.getQueryFactory();

	if (parentMeta != null) {
		parentFrom = QuerydslUtils.getEntityPath(parentMeta.getImplementationClass());
		root = QuerydslUtils.getEntityPath(clazz);

		Path joinPath = (Path) QuerydslUtils.get(parentFrom, parentAttr.getName());
		joinHelper = new JoinRegistry<>(this, queryImpl);

		joinHelper.putJoin(new MetaAttributePath(), root);

		if (addParentSelection) {
			Expression<Object> parentIdExpr = getParentIdExpression(parentMeta, parentAttr);
			querydslQuery = queryFactory.select(parentIdExpr, root);
		}
		else {
			querydslQuery = queryFactory.select(root);
		}

		querydslQuery = querydslQuery.from(parentFrom);
		if (joinPath instanceof CollectionExpression) {
			querydslQuery = querydslQuery.join((CollectionExpression) joinPath, root);
		}
		else {
			querydslQuery = querydslQuery.join((EntityPath) joinPath, root);
		}
	}
	else {
		root = QuerydslUtils.getEntityPath(clazz);
		joinHelper = new JoinRegistry<>(this, queryImpl);
		joinHelper.putJoin(new MetaAttributePath(), root);
		querydslQuery = queryFactory.select(root);
		querydslQuery = querydslQuery.from((EntityPath) root);
	}
}
 
Example #25
Source File: ComputedAttributeQuerydslTest.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Override
protected JpaQueryFactory createQueryFactory(EntityManager em) {
	QuerydslQueryFactory factory = QuerydslQueryFactory.newInstance();

	factory.registerComputedAttribute(TestEntity.class, ATTR_VIRTUAL_VALUE, String.class,
			new QuerydslExpressionFactory<QTestEntity>() {

				@Override
				public Expression<?> getExpression(QTestEntity test, JPAQuery<?> query) {
					return test.stringValue.toUpperCase();
				}
			});

	return factory;
}
 
Example #26
Source File: QuerydslUtils.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Expression<T> get(Expression<?> path, String name) {
	try {
		Class<?> clazz = path.getClass();
		Field field = clazz.getField(name);
		return (Expression<T>) field.get(path);
	}
	catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
		throw new IllegalStateException("failed get field " + path + "." + name, e);
	}
}
 
Example #27
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 4 votes vote down vote up
@Override
public Expression<?> getAttribute(MetaAttributePath attrPath) {
	return joinHelper.getEntityAttribute(attrPath);
}
 
Example #28
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 4 votes vote down vote up
@Override
public Expression<?> getExpression(OrderSpecifier<?> order) {
	return order.getTarget();
}
 
Example #29
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 4 votes vote down vote up
@Override
public Expression<?> joinMapValue(Expression<?> currentCriteriaPath, MetaAttribute pathElement, Object key) {
	MapPath mapPath = (MapPath) QuerydslUtils.get(currentCriteriaPath, pathElement.getName());
	return mapPath.get(key);
}
 
Example #30
Source File: ObjectArrayTupleImpl.java    From katharsis-framework with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T get(Expression<T> expr) {
	throw new UnsupportedOperationException();
}