一、什么是具名参数

在经典的 JDBC 用法中, SQL 参数是用占位符 ? 表示,并且受到位置的限制。定位参数的问题在于, 一旦参数的顺序发生变化, 就必须改变参数绑定。
在 Spring JDBC 框架中, 绑定 SQL 参数的另一种选择是使用具名参数(named parameter)。

具名参数:SQL 按名称(以冒号开头)而不是按位置进行指定,具名参数更易于维护,,也提升了可读性。具名参数由框架类在运行时用占位符取代,
具名参数只在 NamedParameterJdbcTemplate 中得到支持。

NamedParameterJdbcTemplate类拓展了JdbcTemplate类,可以使用全部jdbcTemplate方法。

NamedParameterJdbcTemplate主要提供以下三类方法:execute方法、query及queryForXXX方法、update及batchUpdate方法。

NamedParameterJdbcTemplate可以使用DataSource或JdbcTemplate 对象作为构造器参数初始化。

二、常用API传入参数类型介绍

NamedParameterJdbcTemplate类为命名参数设值有两种方式:java.util.Map 、RowMapper 和 SqlParameterSource。

1. Map<String,?> paramMap

就是一个hash表,好处是可以根据参数名传参,paramMap.put("sqlparamName",value)。

2. RowMapper rowMapper

这个接口为了实现sql查询结果和对象间的转换,可以自己实现,也可以使用系统实现,主要实现类有:

  • SingleColumnRowMapper ,sql结果为一个单列的数据,如List<String> , List<Integer>,String,Integer等
  • BeanPropertyRowMapper, sql结果匹配到对象 List< XxxVO> , XxxVO

3. SqlParameterSource

其作用和Map一样,就是为sql中的条件参数赋值,默认实现有 :

  • MapSqlParameterSource实现非常简单,只是封装了java.util.Map。
  • BeanPropertySqlParameterSource封装了一个JavaBean对象,通过JavaBean对象属性来决定命名参数的值。
  • EmptySqlParameterSource 一个空的SqlParameterSource ,常用来占位使用。
//BeanPropertySqlParameterSource传参方式
SqlParameterSource sps = new BeanPropertySqlParameterSource(javaBean); //MapSqlParameterSource传参方式
SqlParameterSource sps = new MapSqlParameterSource();
//保证参数名和key相同
sps.addValue("key",value);

三、API介绍

1. 查询

(1) 返回单行单列数据

public < T > T queryForObject(String sql, Map<String, ?> paramMap, Class<T> requiredType)
public < T > T queryForObject(String sql, SqlParameterSource paramSource, Class<T> requiredType)

Integer count = template.queryForObject("select count(*) from student", new HashMap<>(), Integer.class);
String name = template.queryForObject( "select name from student where home_address limit 1 ", EmptySqlParameterSource.INSTANCE, String.class);

(2) 返回 (多行)单列 数据

public < T> List< T> queryForList(String sql, Map<String, ?> paramMap, Class< T > elementType)
public < T> List< T> queryForList(String sql, SqlParameterSource paramSource, Class< T> elementType)

List< String> namelist = template.queryForList("select name from student", new HashMap<>(), String.class);

(3) 返回单行数据

public < T> T queryForObject(String sql, Map< String, ?> paramMap, RowMapper< T>rowMapper)
public < T> T queryForObject(String sql, SqlParameterSource paramSource, RowMapper< T> rowMapper)

Student  stu = template.queryForObject(
"select * from student limit 1", new HashMap<>(), new BeanPropertyRowMapper<Student>(Student.class));
//BeanPropertyRowMapper会把下划线转化为驼峰属性
//结果对象可比实际返回字段多或者少

注意:这两个API也可以使用SingleColumnRowMapper返回单行单列数据

String name = template.queryForObject(
"select name from student limit 1", EmptySqlParameterSource.INSTANCE, new SingleColumnRowMapper<>(String.class));

(4) 返回Map形式的单行数据

public Map< String, Object> queryForMap(String sql, Map< String, ?> paramMap)
public Map< String, Object> queryForMap(String sql, SqlParameterSource paramSource)

Map< String, Object> studentMap = template.queryForMap("select * from student limit 1", new HashMap<>());
public < T> List< T> query(String sql, Map< String, ?> paramMap, RowMapper< T> rowMapper)
public < T> List< T> query(String sql, SqlParameterSource paramSource, RowMapper< T> rowMapper)
public < T> List< T> query(String sql, RowMapper< T> rowMapper)

(5) 返回多行数据

public < T> List< T> query(String sql, Map< String, ?> paramMap, RowMapper< T> rowMapper)
public < T> List< T> query(String sql, SqlParameterSource paramSource, RowMapper< T> rowMapper)
public < T> List< T> query(String sql, RowMapper< T> rowMapper)

List< Student> studentList = template.query(
"select * from student",
new BeanPropertyRowMapper<>(Student.class)
);

同理,也可以使用SingleColumnRowMapper返回单行列表List< String>,List< Integer>等。

(6) 返回多行数据(Map)

public List< Map< String, Object>> queryForList(String sql, Map< String, ?> paramMap)
public List< Map< String, Object>> queryForList(String sql, SqlParameterSource paramSource)

List<Map<String, Object>> mapList = template.queryForList(
"select * from student", new HashMap<>());

2. 插入/修改/删除数据,使用updateXXX方法

(1) 使用Map作为参数

int update(String sql, Map<String, ?> paramMap)

Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", UUID.randomUUID().toString());
paramMap.put("name", "小明");
paramMap.put("age", 33);
paramMap.put("homeAddress", "乐山");
paramMap.put("birthday", new Date());
template.update(
"insert into student(id,name,age,home_address,birthday) values (:id,:name,:age,:homeAddress,:birthday)",
paramMap
);

(2) 使用SqlParameterSource作为参数

int update(String sql, SqlParameterSource paramSource)

//使用 BeanPropertySqlParameterSource作为参数
StudentDTO dto=new StudentDTO();//这个DTO为传入数据
dto.setId(UUID.randomUUID().toString());
dto.setName("小红");
dto.setHomeAddress("成都");
//------------------------------
template.update("insert into student(id,name,home_address) values (:id,:name,:homeAddress)",
new BeanPropertySqlParameterSource(dto)); //使用MapSqlParameterSource 作为参数
MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource()
.addValue("id", UUID.randomUUID().toString())
.addValue("name", "小王")
.addValue("homeAddress", "美国");
template.update("insert into student(id,name,home_address) values
(:id,:name,:homeAddress)",mapSqlParameterSource);

四、总结

  • 开发中尽量使用NamedParameterJdbcTemplate代替JdbcTemplate,如果想使用JdbcTemplate,也可以通过NamedParameterJdbcTemplate#getJdbcOperations()获取
  • 不建议使用查询结构为Map的API

【Spring JDBC】NamedParameterJdbcTemplate(四)的更多相关文章

  1. Spring JDBC NamedParameterJdbcTemplate类示例

    org.springframework.jdbc.core.NamedParameterJdbcTemplate类是一个具有基本JDBC操作的模板类,允许使用命名参数而不是传统的’?‘占位符. 这个类 ...

  2. Spring学习进阶(四) Spring JDBC

    Spring JDBC是Spring所提供的持久层技术.主要目的是降低使用JDBC API的门槛,以一种更直接,更简洁的方式使用JDBC API.在Spring JDBC里用户仅需要做哪些比不可少的事 ...

  3. 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】

    一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...

  4. Spring学习(四)——使用Spring JDBC访问数据库

    本篇我们将在上一篇http://www.cnblogs.com/wenjingu/p/3824294.html的Demo程序的基础上增加数据持久层和业务层,实现登录验证功能. 1.修改gradle文件 ...

  5. Spring JDBC

    转载:博客主页:http://blog.csdn.NET/chszs 一.概述 在Spring JDBC模块中,所有的类可以被分到四个单独的包:1)core即核心包,它包含了JDBC的核心功能.此包内 ...

  6. 【Spring JDBC】JdbcTemplate(三)

    传统Jdbc API与Spring jdbcTemplate比较 //JDBC API Statement statement = conn.createStatement(); ResultSet ...

  7. 【Spring JDBC】spring jdbc 介绍(一)

    Spring JDBC模块是Spring框架的基础模块之一.在Spring JDBC模块中,所有的类可以被分到四个单独的包: core 核心包:它包含了JDBC的核心功能.此包内有很多重要的类,包括: ...

  8. spring jdbc 查询结果返回对象、对象列表

    首先,需要了解spring jdbc查询时,有三种回调方式来处理查询的结果集.可以参考 使用spring的JdbcTemplate进行查询的三种回调方式的比较,写得还不错. 1.返回对象(queryF ...

  9. Spring JDBC实现查询

    1 db.properties jdbc.user=root jdbc.password=920614 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbc ...

随机推荐

  1. 如果你不了解Java的JVM,那真的很难进BAT一线大厂!

    前言 对于开发人员来说,如果不了解Java的JVM,那真的是很难写得一手好代码,很难查得一手好bug.同时,JVM也是面试环节的中重灾区.我们不能为了面试而面试,但是学习会这些核心知识你必定会成为面试 ...

  2. 跟着文档学习gulp1.1安装入门

    Step1:检查是否已经安装了node,npm 和 npX是否正确安装 Step2:安装gulp命令行工具(全局安装gulp) npm install --global gulp-cli Step3: ...

  3. Mysql服务彪高排查方式及索引的正确使用步骤

    原文内容来自于LZ(楼主)的印象笔记,如出现排版异常或图片丢失等问题,可查看当前链接:https://app.yinxiang.com/shard/s17/nl/19391737/12af580d-1 ...

  4. 一起学MyBatis之入门篇

    概述 本文以一个简单的小例子,简述在Java项目开发中MyBatis的基本用法,属于入门级文章,仅供学习分享使用,如有不足之处,还请指正. 什么是MyBatis? MyBatis 是一款优秀的持久层框 ...

  5. linux环境下zookeeper下载安装

    步骤一:安装配置jdk环境 1.下载解压jdk-8u221-linux-x64.tar.gz 2.打开 配置文件,vim /etc/profile,添加如下配置,添加完成记得source /etc/p ...

  6. SpringMVC 数据交互

    为什么使用JSON进行数据交互? JSON数据格式比较简单.解析比较方便,在接口调用及HTML页面Ajax调用时较常用. JSON交互方式 请求是Key/Value,响应是JSON(推荐使用) 请求是 ...

  7. 渗透测试初学者的靶场实战 3--墨者学院SQL注入—宽字节盲注

    墨者SQL注入-MYSQL数据库实战环境 实践步骤 1. 决断注入点 输入单引号,提示错误信息: 输入and 1=1 返回页面正常: 输入 and 1=2 返回正常 输入-1,返回异常: 2. 带入s ...

  8. leetcode菜鸡斗智斗勇系列(4)--- 单一数字的乘积和总合的减法

    1.原题: https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ Given an i ...

  9. 从properties中读取配置创建对象

    主要做两个事,从properties配置文件中读取信息,通过反射创建对象 思路主要有两种,遍历得到的属性集合,然后设置类的属性 遍历类的属性集合,从配置文件中读取(不推荐,因为类的属性有多样化,会报错 ...

  10. (转)利用Auto ARIMA构建高性能时间序列模型(附Python和R代码)

    转自:  原文标题:Build High Performance Time Series Models using Auto ARIMA in Python and R 作者:AISHWARYA SI ...