方法是动态构建Predicate
的列表,稍后将其传递给数据库服务对象。为了基于谓词列表创建表连接,我需要确定每个谓词的基础生成类Q *。在谓词上调用getType()
或getClass()
无济于事。
这是我构建谓词的方式:
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);
答案 0 :(得分:2)
不要将生成的Q类型用于动态表达式创建。您可以使用动态路径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
PathExtactor
从给定的Expression