方法动态构建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);
不要将生成的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
中提取第一条路径