本文介绍了QueryDSL:从 Predicate (BooleanExpression) 对象中提取表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一种方法正在动态构建一个 Predicate 列表,然后将其传递给数据库服务对象.为了根据谓词列表创建表连接,我需要确定每个谓词的基础生成类 Q*.在谓词上调用 getType()getClass() 没有帮助.

A method is dynamically building a list of Predicates that is later passed to a database service object. In order to create table joins based on the predicate list I need to determine the underlying generated class Q* of each predicate. Calling getType() or getClass() on the Predicate doesn't help.

这就是我构建谓词的方式:

This is how I build the predicates:

Class<?> tableClazz = Class.forName("foo.bar.database.model.Q"+ WordUtils.capitalize(tableName));
Object tableObj = tableClazz.getConstructor(String.class).newInstance(tableName +"1000");
Field colField = tableClazz.getDeclaredField(fieldName);
Object colObj = colField.get(tableObj);
// method name is one of eq, ne, like...
Method m = colObj.getClass().getMethod(methodName, classParam );
return (Predicate) m.invoke(colObj, operand);

查询构建代码:

JPAQuery query = new JPAQuery(entityManager);
query = query.from(company);
for(Predicate p : predicates){
   // if there's at least one predicat with the underlying db class Foo:
   query = query.join(company.foos, new QFoo());
   break;
}
List<Object[]> rows = query.where(predicates.toArray(new Predicate[0])).listDistinct(company.id);

推荐答案

不要将生成的 Q 类型用于动态表达式创建.您可以使用动态路径代替 http://www.querydsl.com/static/querydsl/2.9.0/reference/html/ch03.html#d0e1379

Don't use the generated Q-types for dynamic Expression creation. You can use dynamic paths instead http://www.querydsl.com/static/querydsl/2.9.0/reference/html/ch03.html#d0e1379

在你的情况下是这样的

Class<?> entityType = Class.forName(...)
PathBuilder entityPath = new PathBuilder(entityType, "entity");
PathBuilder relation = entityPath.get("relation");
Predicate predicate = relation.get...(...).eq(...)

对于路径提取使用这个类 http://www.querydsl.com/static/querydsl/2.9.0/apidocs/com/mysema/query/types/PathExtractor.html

For Path extraction use this class http://www.querydsl.com/static/querydsl/2.9.0/apidocs/com/mysema/query/types/PathExtractor.html

PathExtactor 从给定的 Expression

这篇关于QueryDSL:从 Predicate (BooleanExpression) 对象中提取表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 14:47