我在使用MyBatis 3设置查询参数时遇到问题。我正在使用Select Provider。 这是Mapper界面中的方法:
@SelectProvider(type=my.package.VolunteerSQL.class, method="getQuery")
public List<VolunteerRecord> getOrderedVolunteerList(
@Param("from") int from,
@Param("count") int count,
@Param("orderBy") String[] orderBy,
@Param("filterBy") String[] filterBy,
@Param("filterValue") String filterValue);
以下是Select Provider方法:
public String getQuery(Map<?,?> parameters) {
final String[] orderBy = (String[]) parameters.get("orderBy");
final String[] filterBy = (String[]) parameters.get("filterBy");
String sql = new SQL() {{
SELECT("v.id as id, surname, forename, more columns...");
//SELECT("more columns...");
FROM("volunteer v");
if (filterBy!=null) {
for (int i=0; i<filterBy.length; i++) {
String filter = filterBy[i];
if (i>0) OR();
WHERE(filter+" LIKE '%#{filterValue}%'");
}
}
GROUP_BY("vs.volunteer_id");
for (String order : orderBy) {
ORDER_BY(order);
}
}}.toString();
String result = sql+" LIMIT #{from},#{count}";
System.out.println("SQL="+result);
return result;
}
这里有几个问题。 首先,如果我有任何过滤器,我会得到这个例外:
Error querying database. Cause: java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2).
生成的SQL似乎没有足够的参数占位符用于我的参数,但是当我检查SQL时它看起来没问题。不知道那里发生了什么。
其次,过滤列对SQL注入攻击是开放的,因为我不能为它们使用参数,我必须将它们直接连接到SQL字符串中。有一个很好的,干净的替代品是安全的吗?