場景:MyBatis 物理分頁,查詢條件中須要用到foreach ,參數失效,查不到結果 java
分析:把java.sql的debug打開,sql語句正常,參數也正常。debug物理分頁代碼,setParameters時,boundSql.getAdditionalParameter(propertyName)獲取值始終是null,沒有拿到參數。可是BoundSql的metaParameters中能夠看到相關的參數值。 sql
解決方法: app
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); .net
ReflectUtil 代碼: debug
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);
}
}
} 對象