gpt4 book ai didi

QueryDSL:从 PathBuilder 生成谓词

转载 作者:行者123 更新时间:2023-12-02 22:12:30 26 4
gpt4 key购买 nike

如何用 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() 但不能调用 like()、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;

最佳答案

你应该这样使用它

// 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%");

关于QueryDSL:从 PathBuilder 生成谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15273542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com