QueryDSL:从PathBuilder生成谓词

时间:2013-03-07 14:18:52

标签: querydsl

如何使用PathBuilder替换使用生成的Q *类和java反射的以下方法?

// member vars:
T operand;  // can be a BigDecimal or a String
String tableName;
String fieldName;
String methodName;

public Predicate asPredicate()
{
   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);

   Class classParam = Object.class;
   if(methodName.matches(".*like"){
     classParam = String.class;
   }
   // method name is one of eq, ne, like...
   Method m = colObj.getClass().getMethod(methodName, classParam );
   return (Predicate) m.invoke(colObj, operand);
}

这很有效,但我建议使用PathBuilder来回答我的另一个问题https://stackoverflow.com/questions/15269845/querydsl-extract-table-name-from-predicate-booleanexpression-object),这也会删除尴尬的newInstance(tableName +“1000”)。

PathBuilder<?> entityPath = new PathBuilder("foo.bar.database.model.Q"+ WordUtils.capitalize(tableName), "entity"); // what does the second param stand for?
PathBuilder relation = entityPath.get(fieldName);
// ???

两个问题: 1)我现在可以在关系上调用eq()或ne()但不喜欢(),notLike() 2)如何获取colObj以便我可以使用java反射colObj.getClass()。getMethod(...)

溶液: 感谢Timo的回答,除了两个instanceof条件之外我完全放弃了反思,现在使用这个代码:

tableClazz = Class.forName("foo.bar.database.model."+ WordUtils.capitalize(tableName));
PathBuilder<?> entityPath = new PathBuilder(tableClazz, tableName +"1000");
Predicate predicate = null;

if(operand instanceof String){
   StringPath path = entityPath.getString(fieldName);
   switch(type){
       case EQ:
          predicate = path.eq((String) operand);
       case CONTAINS:
          predicate = path.like("%" + operand +"%");
          break;
      // snip BEGINS WITH, ENDS WITH
    }
}else if(operand instanceof BigDecimal){
    assert(type.equals(Type.EQ));
    NumberPath<BigDecimal> path = entityPath.getNumber(fieldName, BigDecimal.class);
    predicate = path.eq((BigDecimal) operand);
}
if(negation){
  return predicate.not();
}
return predicate;

1 个答案:

答案 0 :(得分:7)

你应该像这样使用它

// entityClass is the entity type, not the Q-type
Class<?> entityClass = Class.forName(...)
// "entity" is the variable name of the path
PathBuilder<?> entityPath = new PathBuilder(entityClass, "entity"); 
// use getString to get a String path
Predicate predicate = entityPath.getString("property").like("a%");