我想效仿其他这样的示例,例如How to use SELECT IN clause in JDBCTemplates?在查询中使用in子句,但是我从queryForInt收到此错误:

The method queryForInt(String, Object[]) in the type JdbcTemplate is not applicable for the arguments (String, Map)


这是我的代码:

    List groupList = getGroupsForUser(username);


    List<String> groupPara = new ArrayList<String>();

    for (Iterator groups = groupList.iterator(); groups.hasNext();) {
        Group g = (Group) groups.next();
        groupPara.add(g.getGroupName());
    }
    Map namedParameters = Collections.singletonMap("listOfValues", groupPara);

    int groupPermissions = getJdbcTemplate().queryForInt( "SELECT MAX(roleid) FROM groupaccess "
            + "WHERE inode = '"+inode.getId()+"' AND groupname in (:listOfValues)", namedParameters);

    return groupPermissions;


尽管这样做不是很优雅,但我还是可以通过它来工作的:

List groupList = getGroupsForUser(username);
String groupPara = ("(");
Object[] params = new Object[groupList.size()+1];
params[0]=inode.getId();
int index = 1;
for (Iterator groups = groupList.iterator(); groups.hasNext();) {
    Group g = (Group) groups.next();
    params[index]=g.getGroupName();
    index++;
    groupPara += " ? ,";
}
groupPara = groupPara.substring(0, groupPara.length() - 1);
groupPara+=")";

int groupPermissions = getJdbcTemplate().queryForInt( "SELECT MAX(roleid) FROM groupaccess "
        + "WHERE inode = ? AND groupname in "+groupPara, params);

return groupPermissions;

最佳答案

jdbcTemplate没有任何方法queryForInt(String, Map)。相反,您需要使用NamedParameterJdbcTemplate。即:

Map<String,Object> namedParameters = Collections.singletonMap("listOfValues", groupPara);

int groupPermissions = namedParameterJdbcTemplate.queryForInt( "SELECT MAX(roleid) FROM groupaccess "
        + "WHERE inode = '"+inode.getId()+"' AND groupname in (:listOfValues)", namedParameters);


或者下面有一种解决方法:

Set<Integer> ids = groupPara;

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("listOfValues", ids);

List<Integer> foo = getJdbcTemplate().queryForInt( "SELECT MAX(roleid) FROM groupaccess "
            + "WHERE inode = '"+inode.getId()+"' AND groupname in (:listOfValues)", getRowMapper(), namedParameters);

09-25 21:06