9

I want to pass list values in IN clause using jdbcTemplate in mysql query. Like below,

 List<Long> listId= new ArrayList<>();
 listId.add(1234L);
 listId.add(1235L);
 listId.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 to achieve this in best way?

MMMMS
  • 2,179
  • 9
  • 43
  • 83

2 Answers2

15

NamedParameterJdbcTemplate may help for you.

For your sample, try this please:)

NamedParameterJdbcTemplate jdbcTemplate = ...

List<Long> listId= new ArrayList<>();
listId.add(1234L);
listId.add(1235L);
listId.add(1236L);

String sql="select column1,column2  from table where columName in(:ids)";
List<BojoClass> result = new ArrayList<>();
Map idsMap = Collections.singletonMap("ids", listId);
result = jdbcTemplate.query(sql, idsMap, ParameterizedBeanPropertyRowMapper.newInstance(BojoClass.class));

Edited:

If you can get DataSource, you can just init a NamedParameterJdbcTemplate object by its constructor like:

NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource());
Blank
  • 12,308
  • 1
  • 14
  • 32
1

You can join your list with StringUtils.join(paramListForInClause, ","); to generate the string you need

luso
  • 2,812
  • 6
  • 35
  • 50
  • 4
    Like people said in another topic - https://stackoverflow.com/a/39788183/3800377. "listeParamsForInClause wont be escaped and makes you vulnerable to SQL injection." – Vladislav Kysliy Oct 29 '18 at 18:37