(转)NamedParameterJdbcTemplate常用方法总结


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

转自:NameParameterJdbcTemplate常用方法总结


文章作者: Cody_
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Cody_ !
评论
 上一篇
定时任务-暂停、开始、更新、删除 定时任务-暂停、开始、更新、删除
对于后端开发来说,定时任务的使用频率非常高,当然也少不了定时任务的管理了。最常见的应用就是单节点定时任务持久化的实现,需求稍微多一点就需要对定时任务管理,暂停、删除、恢复等;本文在SpringBoot&quartz的项目上讲解; 单
2019-05-14
下一篇 
FastJSON的常用方法 FastJSON的常用方法
FastJSON是阿里巴巴内部开发的用于后台处理json格式数据的一个工具包,项目中基本使用这个工具包,如下举例FastJSON工具的常用方法: 将实体类转为json格式的字符串 JSON.toJSONString(Bean);
2019-05-07
  目录