jdbcmysqlin参数化_JdbcTemplate中向in语句传参
spring jdbc包提供了JdbcTemplate和它的两个兄弟SimpleJdbcTemplate和NamedParameterJdbcTemplate,我们先从JdbcTemplate⼊⼿,
引⼊问题,领略⼀下类NamedParameterJdbcTemplate在处理where中包含in时的便利和优雅。
⾸先创建实体类Employee:
1 public classEmployee {
2 privateLong id;
3 privateString name;
4 privateString dept;
5 //omit toString, getters and setters
6 }
使⽤JdbcTemplate访问⼀批数据
⽐较熟悉的使⽤⽅法如下:
public List queryByFundid(intfundId) {
String sql= "select * from employee where id = ?";
Map args = new HashMap<>();
args.put("id", 32);return jdbcTemplate.queryForList(sql, args , Employee.class);
}
但是,当查询多个部门,也就是使⽤in的时候,这种⽅法就不好⽤了,只⽀持Integer.class String.class 这种单数据类型的⼊参。如果⽤List匹配问号,你会发现出现这种的SQL:
select * from employee where id in ([1,32])
执⾏时⼀定会报错。解决⽅案——直接在Java拼凑⼊参,如:
String ids = "3,32";
String sql= "select * from employee where id in (" + ids +")";
如果⼊参是字符串,要⽤两个''号引起来,这样跟数据库查询⽅式相同。⽰例中的⼊参是int类型,就没有使⽤单引号。但是,推荐使⽤NamedParameterJdbcTemplate类,然后通过: ids⽅式进⾏参数的匹配。
使⽤NamedParameterJdbcTemplate访问⼀批数据
public List queryByFundid(intfundId) {
String sql= "select * from employee where id in (:ids) and dept = :dept";
Map args = new HashMap<>();
args.put("dept", "Tech");
List ids = new ArrayList<>();
ids.add(3);
ids.add(32);
args.put("ids", ids);
NamedParameterJdbcTemplate givenParamJdbcTemp= newNamedParameterJdbcTemplate(jdbcTemplate);
List data = givenParamJdbcTemp.queryForList(sql, args, Employee.class);returndata;
}
如果运⾏以上程序,会采坑,抛出异常:org.springframework.jdbc.IncorrectResultSetColumnCountException: Incorrect column count: expected 1, actual 3。
抛出此异常的原因是⽅法queryForList 不⽀持多列,但是,API(spring-jdbc-4.3.17.RELEASE.jar)并未说明。请看queryForList 在JdbcTemplate的实现:
public List queryForList(String sql, SqlParameterSource paramSource, ClasselementType)throwsDataAccessException {return query(sql, paramSource, new SingleColumnRowMapper(elementType));
}/*** Create a new {@codeSingleColumnRowMapper}.
*
Consider using the {@link#newInstance} factory method instead,
* which allows for specifying the required type once only.
*@paramrequiredType the type that each result object is expected to match*/
public SingleColumnRowMapper(ClassrequiredType) {
setRequiredType(requiredType);
}
查询API发现,需要换⼀种思路,代码如下:
public List queryByFundid(intfundId) {
String sql= select * from employee where id in (:ids) and dept =:dept
Map args = new HashMap<>();
args.put("dept", "Tech");
List ids = new ArrayList<>();
ids.add(3);
ids.add(32);
args.put("ids", ids);
NamedParameterJdbcTemplate givenParamJdbcTemp= newNamedParameterJdbcTemplate(jdbcTemplate);
List data = givenParamJdbcTemp.jdbc.query(sql, args, new RowMapper() {
@Overridepublic Employee mapRow(ResultSet rs, int index) throwsSQLException {
Employee emp= newEmployee();
emp.Long("id"));
emp.String("name"));
emp.String("dept"));returnemp;
}jdbctemplate查询一条数据
});returndata;
}
欢迎拍砖。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。