JdbcTemplate中向in语句传参

JdbcTemplate中向in语句传参

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

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

首先创建实体类Employee: 

public class Employee {
	private Long id;
	private String name;
	private String dept;
	// omit toString, getters and setters
}

 

使用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方式进行参数的匹配。

使用NamedParameterJdbcTemplate访问一批数据

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 3。

抛出此异常的原因是方法queryForList 不支持多列,但是,API(spring-jdbc-4.3.17.RELEASE.jar)并未说明。请看queryForList 在JdbcTemplate的实现:

public <T> List<T> queryForList(String sql, SqlParameterSource paramSource, Class<T> elementType)
            throws DataAccessException {
        return query(sql, paramSource, new SingleColumnRowMapper<T>(elementType));
    }

/**
 * Create a new {@code SingleColumnRowMapper}.
 * <p>Consider using the {@link #newInstance} factory method instead,
 * which allows for specifying the required type once only.
 * @param requiredType the type that each result object is expected to match
 */
public SingleColumnRowMapper(Class<T> requiredType) {
   setRequiredType(requiredType);
}

查询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;
}

 欢迎拍砖。

 

转自:https://www.cnblogs.com/east7/p/9762742.html
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值