MyBatis 物理分页foreach 参数失效
**场景:**MyBatis 物理分页,查询条件中需要用到foreach ,参数失效,查不到结果
**分析:**把java.sql的debug打开,sql语句正常,参数也正常。debug物理分页代码,setParameters时,boundSql.getAdditionalParameter(propertyName)获取值始终是null,没有拿到参数。但是BoundSql的metaParameters中可以看到相关的参数值。
解决方法:
BoundSql countBS = new BoundSql(configuration, sql, boundSql.getParameterMappings(), parameterObject);
Field metaParamsField = ReflectUtil.getFieldByFieldName(boundSql, "metaParameters");
if (metaParamsField != null) {
MetaObject mo = (MetaObject) ReflectUtil.getValueByFieldName(boundSql, "metaParameters");
ReflectUtil.setValueByFieldName(countBS, "metaParameters", mo);
}
setParameters(prepStat, configuration, countBS, parameterObject);
ReflectUtil 代码:
public class ReflectUtil {
/**
* 获取obj对象fieldName的Field
*
* @param obj
* @param fieldName
* @return
*/
public static Field getFieldByFieldName(Object obj, String fieldName) {
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
return superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
}
}
return null;
}
/**
* 获取obj对象fieldName的属性值
*
* @param obj
* @param fieldName
* @return
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static Object getValueByFieldName(Object obj, String fieldName) throws SecurityException,
NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = getFieldByFieldName(obj, fieldName);
Object value = null;
if (field != null) {
if (field.isAccessible()) {
value = field.get(obj);
} else {
field.setAccessible(true);
value = field.get(obj);
field.setAccessible(false);
}
}
return value;
}
/**
* 设置obj对象fieldName的属性值
*
* @param obj
* @param fieldName
* @param value
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void setValueByFieldName(Object obj, String fieldName, Object value) throws SecurityException,
NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = getFieldByFieldName(obj, fieldName);
if (field.isAccessible()) {
field.set(obj, value);
} else {
field.setAccessible(true);
field.set(obj, value);
field.setAccessible(false);
}
}
}
具体是怎么解决的啊
楼主说的是在哪里添加代码,没看太懂。我的是pagehelper4.1.1
:idea: :idea: :idea: :idea: 高人高人,佩服
void processIntercept(final Object queryArgs) { //queryArgs = query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) MappedStatement ms = (MappedStatement)queryArgs; Object parameter = queryArgs; final RowBounds rowBounds = (RowBounds)queryArgs; int offset = rowBounds.getOffset(); int limit = rowBounds.getLimit();
:D , 我的就是这个问题,解决了,3Q
lz给力,foreach分页解决了,受教,受教了......