码迷,mamicode.com
首页 > 数据库 > 详细

jdbcTemplate中向in语句传参

时间:2018-10-09 21:51:02      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:字符串   它的   count   col   list   turn   data   pre   jdbc   

spring jdbc包提供了JdbcTemplate和它的两个兄弟SimpleJdbcTemplate和NamedParameterJdbcTemplate,我们先从JdbcTemplate入手,

引入问题,领略一下类NamedParameterJdbcTemplate在处理where中包含in时的便利和优雅。

首先创建实体类Employee: 

1 public class Employee {
2     private Long id;
3     private String name;
4     private String dept;
5     // omit toString, getters and setters
6 }

 

使用JdbcTemplate访问一批数据

比较熟悉的使用方法如下:

public List<Employee> queryByFundid(int fundId) { 
   String sql = "select * from employee where id = ?"; 
   Map<String, Object> 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方式进行参数的匹配。

public List<Employee> queryByFundid(int fundId) { 
     String sql = "select * from employee where id in (:ids) and dept = :dept";

    Map<String, Object> args  = new HashMap<>();
args.put("dept", "Tech"); List
<Integer> ids = new ArrayList<>(); ids.add(3); ids.add(32); args.put("ids", ids); NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate); List<Employee> data = givenParamJdbcTemp.queryForList(sql, args, Employee.class); return data; }

如果运行以上程序,会采坑,抛出异常:org.springframework.jdbc.IncorrectResultSetColumnCountException: Incorrect column count: expected 1, actual 6。

查询API发现,需要换一种思路,代码如下:

public List<Employee> queryByFundid(int fundId) { 
    String sql = select * from employee where id in (:ids) and dept = :dept

    Map<String, Object> args  = new HashMap<>();
    args.put("dept", "Tech");
    List<Integer> ids = new ArrayList<>();
    ids.add(3);
    ids.add(32);
    args.put("ids", ids);
    NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate);
    List<Employee> data = givenParamJdbcTemp.jdbc.query(sql, args, new RowMapper<Employee>() {
            @Override
            public Employee mapRow(ResultSet rs, int index) throws SQLException {
                Employee emp = new Employee();
                emp.setId(rs.getLong("id"));
                emp.setName(rs.getString("name"));
                emp.setDept(rs.getString("dept"));
                return emp;
            }
        });
    return data;
}

 

欢迎拍砖。

 

jdbcTemplate中向in语句传参

标签:字符串   它的   count   col   list   turn   data   pre   jdbc   

原文地址:https://www.cnblogs.com/east7/p/9762742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!