zoukankan      html  css  js  c++  java
  • JdbcTemplate中向in语句传参

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

    使用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;
    }

     欢迎拍砖。

  • 相关阅读:
    CSS常用伪类
    HTML5常用API
    HTML5新技术FormData提交表单数据
    WebPack打包后如何调试
    layui的初体验(layer的使用)
    java数组
    java:注解
    java反射:框架设计的灵魂
    885历年编程题
    2020年专业课编程题
  • 原文地址:https://www.cnblogs.com/east7/p/9762742.html
Copyright © 2011-2022 走看看