当前使用版本(必填,否则不予处理)
3.5.1
请问怎么样根据fieldname生成SFunction 根据SFunction获取fieldname网上有很多 怎么根据fieldname生成SFunction呢
比如我有一个Person类 里面有name属性 我怎么根据name这个字符串和Person这个class 获取SFunction
Comment From: VampireAchao
很棒的问题
Comment From: shuaizai88
public static SFunction getSFunction(Class<?> entityClass, String fieldName) { if (functionMap.containsKey(entityClass.getName() + fieldName)) { return (SFunction)functionMap.get(entityClass.getName() + fieldName); } else { Field field = getDeclaredField(entityClass, fieldName); if (field == null) { throw ExceptionUtils.mpe("This class %s is not have field %s ", new Object[]{entityClass.getName(), fieldName}); } else { SFunction func = null; MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodType methodType = MethodType.methodType(field.getType(), entityClass); String getFunName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try {
CallSite site = LambdaMetafactory.altMetafactory(lookup, "invoke", MethodType.methodType(SFunction.class), methodType, lookup.findVirtual(entityClass, getFunName, MethodType.methodType(field.getType())), methodType, 1);
func = site.getTarget().invokeExact();
functionMap.put(entityClass.getName() + field, func);
return func;
} catch (Throwable var9) {
throw ExceptionUtils.mpe("This class %s is not have method %s ", new Object[]{entityClass.getName(), getFunName});
}
}
}
}
参考这里面的改一下把。 完整代码在:https://gitee.com/baomidou/mybatis-plus-advance/blob/master/src/main/java/com/baomidou/mybatisplus/advance/injector/FuntionTools.java
Comment From: VampireAchao
见:https://gitee.com/baomidou/mybatis-plus/blob/3.0/mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/toolkit/LambdaUtilsTest.java#L49
Comment From: elcnu986
见:https://gitee.com/baomidou/mybatis-plus/blob/3.0/mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/test/toolkit/LambdaUtilsTest.java#L49
`// 通用的检查方法
private
// 使用lambdaQuery查询记录是否存在
boolean exists = entityMapper.exists(Wrappers.<T>lambdaQuery()
.eq(new SFunction<T, Long>() {
@Override
public Long apply(T t) {
try {
return (Long) getIdMethod.invoke(t);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}, entityId)
);
if (!exists) {
throw new RuntimeException("错误的id");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}`
这是报错信息: Error evaluating expression 'ew.sqlSegment != null and ew.sqlSegment != '''. Cause: org.apache.ibatis.ognl.OgnlException: sqlSegment [com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: java.io.NotSerializableException: org.example.test.MyTest]