NamedParameterJdbcTemplate类拓展了JdbcTemplate类,对JdbcTemplate类进行了封装从而支持命名参数特性。
NamedParameterJdbcTemplate主要提供以下三类方法:execute方法、query及queryForXXX方法、update及batchUpdate方法。
1、插入/修改/删除数据,使用updateXXX方法
使用map作为参数
Map<String, Object> map = new HashMap<>(1);
StringBuffer sql = new StringBuffer();
sql.append("select name from student where name like :name");
map.put("name", "%" + "管理员" + "%");
template.update(sql.toString(), map);
使用Bean作为参数
Bean bean = new Bean();
bean.setName("管理员");
template.update(sql, new BeanPropertySqlParameterSource(bean));
使用MapSqlParameterSource作为参数
MapSqlParameterSource source = new MapSqlParameterSource()
.addValue("name", "管理员");
template.update(sql, source);
2、查询
返回单行单列数据
map.put("name", "管理员");
Integer count = template.queryForObject("select count(1) from student where name = :name", map, Integer.class);
// String 则用 String.class 接收;
返回多行单列数据
List<String> nameList = template.queryForList(sql, map, String.class);
返回单行数据
Bean bean = template.queryForObject("select * from student where id = :id", map, new BeanPropertyRowMapper<Bean>(Bean.class));
// BeanPropertyRowMapper会把下划线转化为驼峰属性
// 结果对象可比实际返回字段多或者少
返回Map形式的单行数据
Map<String, Object> result = template.queryForMap(sql, map);
返回多行数据
List<Bean> beanList = template.query(sql, new BeanPropertyRowMapper<>(Bean.class));
// 同理,也可以使用SingleColumnRowMapper返回单行列表List< String>,List< Integer>等
返回多行数据(Map)
List<Map<String, Object>> map = template.queryForList(sql, map);