關於jdbcTemplate和NamedParameterJdbcTemplate 的用法心得
專案中用到了需要根據條件 in 去查詢條件,但是jdbcTemplate不能滿足這個,所有采用NamedParameterJdbcTemplate 配合具名引數的使用來 實現:
附上程式碼:
String sql = "SELECT * FROM SMP where S_BS in (:branchs) and S_BS027_DATASRC = :chanel ORDER BY (S_PL066_LOGINGCOUNTSLASTTHREE+0) DESC";
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
HashMap<String, Object> parameters = new HashMap<String,Object>();
parameters.put("chanel", chanel);
parameters.put("branchs", branchCodes);
/*MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("branchCodes",Arrays.asList(s));*/
RowMapper<ItemResult> rm = BeanPropertyRowMapper.newInstance(ItemResult.class);
// List<ItemResult> list = namedParameterJdbcTemplate.queryForList(sql, parameters,ItemResult.class );
List<ItemResult> list = namedParameterJdbcTemplate.queryForList(sql, parameters,ItemResult.class );
return list;
在這裡說明幾點:
1 (:branchs)這種具名引數,瞭解下,類似於佔位符
2 在oracle中 long型別的資料不能使用order by 或者 grou by ,所有數字排序問題還是採用varchar型別,在sql中,(S_PL066_LOGINGCOUNTSLASTTHREE+0)可以轉換成數字。
3 List<ItemResult> list = namedParameterJdbcTemplate.queryForList(sql, parameters,ItemResult.class ); 剛開始我使用的這個方法,然而時不可以的,這個方法只能正對於那種查詢出來只有一個object的型別,否則會報錯:預期只有一個結果,查出來卻有n個結果集。查看了下原始碼,只支援一個物件,所有采用List<ItemResult> list = namedParameterJdbcTemplate.queryForList(sql, parameters,ItemResult.class );完美解決問題。
最後附上jdbcTemplate的批量插入:
sql = "INSERT INTO SMP_"
+ "(S_BS,S_BS016_BID2,S_BSE,S_PL028_ST,S_BS02ID)"
+ " VALUES(?,?,?,?,?,?,?,)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, result.get(i).getS1);
ps.setString(2, result.get(i).getS2);
ps.setString(3, result.get(i).getS_2);
ps.setString(4, result.get(i).getS_3);
ps.setString(5, result.get(i).getS_4);
}
@Override
public int getBatchSize() {
logger.info("共插入"+result.size()+"條資料!");
return result.size();
}
});