简体   繁体   中英

select query where in clause problem in spring jdbcTemplate

public class CountryMasterModel { private String countryNames[];

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

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

}

public interface CountryMasterService {

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

}

@Component public class CountryMasterDAO implements 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());
}

}

enter image description here

Check this line:

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

NAME IN (?) is requiring one param and new Object[] { ids } has 3 params. try this NAME IN (?,?,?)

check this link for more information: https://www.baeldung.com/spring-jdbctemplate-in-list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM