如何使用jdbcTemplate在IN子句中传递list参数

MMM*_*MMS 7 mysql jdbctemplate

我想在mysql查询中使用jdbcTemplate在IN子句中传递列表值.如下,

 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));
Run Code Online (Sandbox Code Playgroud)

如何以最佳方式实现这一目标?

Bla*_*ank 12

NamedParameterJdbcTemplate 可能会对你有所帮助.

对于您的样品,请试试这个:)

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));
Run Code Online (Sandbox Code Playgroud)

编辑:

如果你能得到DataSource,你可以NamedParameterJdbcTemplate通过它的构造函数初始化一个对象,如:

NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource());
Run Code Online (Sandbox Code Playgroud)