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

 歡迎拍磚。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM