Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass list of values as a parameter to IN clause using jdbc template [duplicate]

I want to pass the car names as a bind variable (changes at runtimme) How to achieve that .

Java Version 1.7

private JdbcTemplate jdbcTemplate;

 public Collection<Cars> findAll(){

 String sql =  "SELECT NAME, YEAR, TYPE FROM CARS where NAME in ('Honda','Audi','Benz')";
        List<Cars> carsList = new ArrayList<Cars>();
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
        for (Map row : rows) {
            Cars car = new Cars();
            car.setName(String.valueOf(row.get("NAME")));
            car.setType(String.valueOf(row.get("TYPE")));
            car.setYear(String.valueOf(row.get("YEAR")));

            carsList.add(car);
        }
        return carsList;
    }
like image 902
Jan69 Avatar asked Aug 15 '17 15:08

Jan69


People also ask

How do I convert a string to a list in JDBC query?

add(1236L); String type ="A"; List<BojoClass> result = new ArrayList<>(); String sql="select column1,column2 from table where columName in(?)" result = jdbcTemplate. query(sql, new Object[]{listId}, new BeanPropertyRowMapper<BojoClass>(BojoClass. class));

How do you pass a list of objects in SQL query?

All you have to do is build the comma separated list of items and insert it in the string.

What is JdbcTemplate queryForObject?

queryForObject() is a method provided by JdbcTemplate , which is used to fetch the single record from the database. queryForObject() takes 3 parameters, sql_query , row_mapper and parameter.


2 Answers

Use named parameters as explained here, e.g.:

String sql =  "SELECT NAME, YEAR, TYPE FROM CARS where NAME in (:cars)";
List<Cars> carsList = new ArrayList<Cars>();
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(datasource);
List<String> carNames = new ArrayList<String>();
for(Car car : carList){
    carNames.add(car.getName());
}
SqlParameterSource namedParameters = new MapSqlParameterSource("cars", carNames);
namedParameterJdbcTemplate.queryForObject(sql, namedParameters, ResponseType.class);
like image 85
Darshan Mehta Avatar answered Oct 13 '22 08:10

Darshan Mehta


jdbcTemplate.queryForList(
    "SELECT NAME, YEAR, TYPE FROM CARS where NAME in (?,?,?)",
    new Object[] { "Honda", "Audi", "Benz" }
);

You should probably wrap the logic into a method that accepts the IN values and generates appropriate sequence of question marks.

Some frameworks (like MyBatis) have built-in support for this.

Also keep in mind that different DBs have different limits on how long the IN list (or query as whole) may be. If you have too many values to put in the IN clause, you'll have to handle this (break it down to "batches" of appropriate size or use a different approach altogether).

like image 1
Jiri Tousek Avatar answered Oct 13 '22 09:10

Jiri Tousek