help
help

Reputation: 851

SELECT IN clause in JDBCTemplates is not working

I am tying to follow other example like this How to use SELECT IN clause in JDBCTemplates? to use in clause in my query, but I am getting this error from queryForInt:

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

This is my code:

    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;

I got it to work by doing this, although is not very elegant:

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;

Upvotes: 2

Views: 3353

Answers (1)

Jatin
Jatin

Reputation: 31724

jdbcTemplate does not have any method queryForInt(String, Map). Instead you need to use NamedParameterJdbcTemplate . i.e:

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

Or there is a workaround below:

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

Upvotes: 2

Related Questions