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

自闭症网瘾萝莉.ら 提交于 2020-12-05 05:03:53

问题


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?


回答1:


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());



回答2:


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



来源:https://stackoverflow.com/questions/37518094/how-to-pass-list-parameter-in-in-clause-using-jdbctemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!