首页 > 解决方案 > 在spring jdbcTemplate中选择查询where in子句问题

问题描述

公共类 CountryMasterModel { 私有字符串 countryNames[];

public String[] getCountryNames() {
    return countryNames;
}

public void setCountryNames(String[] countryNames) {
    this.countryNames = countryNames;
}

}

公共接口 CountryMasterService {

List<String> getCountryData(String compCode, CountryMasterModel model) throws SQLException, DataAccessException;

}

@Component 公共类 CountryMasterDAO 实现 CountryMasterService{

@Autowired
private JdbcTemplate template;

@Override
public List<String> getCountryData(CountryMasterModel model) throws SQLException, DataAccessException {
    this.template = new JdbcTemplate(DBMSSQL.getDBCon());
    System.out.println(template.getDataSource().getConnection().getCatalog());
    List<String> ids = Arrays.asList(model.getCountryNames());
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("countryName", ids);
    List<String> list = new ArrayList<String>();
    list = this.template.query("SELECT NAME FROM country_master WHERE NAME IN (?)", new Object[] { ids },
            new CountryMasterResultSetExtrator());
    System.out.println("ids = " + ids);
    System.out.println("list = " + list.get(0));
    return list;
}

public static void main(String[] args) throws DataAccessException, SQLException {
    CountryMasterModel bean = new CountryMasterModel();
    String a[] = { "India", "Pakistan", "Russia", "America",};
    bean.setCountryNames(a);
    System.out.println(StringUtil.getStringArray(a));
    List<String> list = new CountryMasterDAO().getCountryData(bean);
    System.out.println("List Size = "+list.size());
}

}

在此处输入图像描述

标签: javaspringspring-mvc

解决方案


检查这一行:

list = this.template.query(
          "SELECT NAME FROM country_master WHERE NAME IN (?)", 
           new Object[] { ids },
            new CountryMasterResultSetExtrator()
       );

NAME IN (?)需要一个参数并且new Object[] { ids }有 3 个参数。尝试这个NAME IN (?,?,?)

查看此链接以获取更多信息: https ://www.baeldung.com/spring-jdbctemplate-in-list


推荐阅读