Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass list parameter in IN clause using jdbcTemplate [duplicate]

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?

like image 750
MMMMS Avatar asked May 30 '16 05:05

MMMMS


People also ask

How do you pass a list of strings in JdbcTemplate 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 values in SQL query?

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

How do you use RowMapper?

Usage. Step 1 − Create a JdbcTemplate object using a configured datasource. Step 2 − Create a StudentMapper object implementing RowMapper interface. Step 3 − Use JdbcTemplate object methods to make database operations while using StudentMapper object.


2 Answers

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());
like image 150
Blank Avatar answered Oct 09 '22 06:10

Blank


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

like image 43
luso Avatar answered Oct 09 '22 07:10

luso