一種方法是動態構建一個Predicate
列表,稍後傳遞給數據庫服務對象。爲了創建基於謂詞列表的表連接,我需要確定每個謂詞的基礎生成類Q *。在Predicate上調用getType()
或getClass()
並沒有幫助。QueryDSL:從謂詞(布爾表達式)對象中提取表名
這是我建立的謂詞:
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);
哪個Querydsl你正在使用模塊,JPA,SQL還是其他? – 2013-03-07 11:31:46
我正在使用JPA。生成的Q *類擴展com.mysema.query.types.path.EntityPathBase – 2013-03-07 11:46:05