当前位置:Gxlcms > 数据库问题 > jdbcTemplate中向in语句传参

jdbcTemplate中向in语句传参

时间:2021-07-01 10:21:17 帮助过:7人阅读

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   

人气教程排行