一种方法正在动态构建一个Predicate
s 列表,该列表稍后将传递给数据库服务对象。为了基于谓词列表创建表连接,我需要确定每个谓词的基础生成类 Q*。在谓词上调用getType()
orgetClass()
没有帮助。
这就是我构建谓词的方式:
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);