JDBCTemplates中的SELECT IN子句不起作用

时间:2013-10-01 18:15:15

标签: java jdbctemplate

我想跟随其他示例如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;

1 个答案:

答案 0 :(得分:2)

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);