一:JdbcTemplate概述及入门
“Don‘t Reinvent the Wheel” , 这是一句很经典的话,出自Spring官方,翻译过来就是说 “不要重复发明轮子” 。由此我们可以猜测,JdbcTemplate的存在使我们开发人员可以摒弃JDBC的原始开发模式,使我们不必重复性的写JDBC原生代码。所以说Spring为了开发的效率,顺带着写了一套JdbcTemplate的模板工具类,它对原始的JDBC有着一个封装,通过模板设计模式帮我们消除了冗余的代码;有经验的朋友们应该会很清楚的知道dbutils工具类,它的封装和JdbcTemplate封装有着相似之处,都是为了简化JDBC开发的方便。
Tips:大家凡是在Spring中看到xxxTemplate,就是说明被封装了一个模板类
1:JdbcTemplate类支持的回调类
(一):预编译语句及存储过程创建回调:用于根据JdbcTemplate提供的连接创建相应的语句 ①:PreparedStatementCreator: 通过回调获取JdbcTemplate提供的Connection,由用户使用该Conncetion创建相关的PreparedStatement; ②:CallableStatementCreator: 通过回调获取JdbcTemplate提供的Connection,由用户使用该Conncetion创建相关的CallableStatement; (二):预编译语句设值回调:用于给预编译语句相应参数设值 ①:PreparedStatementSetter: 通过回调获取JdbcTemplate提供的PreparedStatement,由用户来对相应的预编译语句相应参数设值; ②:BatchPreparedStatementSetter: 类似于PreparedStatementSetter,但用于批处理,需要指定批处理大小; (三):自定义功能回调:提供给用户一个扩展点,用户可以在指定类型的扩展点执行任何数量需要的操作 ①:ConnectionCallback: 通过回调获取JdbcTemplate提供的Connection,用户可在该Connection执行任何数量的操作; ②:StatementCallback: 通过回调获取JdbcTemplate提供的Statement,用户可以在该Statement执行任何数量的操作; ③:PreparedStatementCallback: 通过回调获取JdbcTemplate提供的PreparedStatement,用户可以在该PreparedStatement执行任何数量的操作; ④:CallableStatementCallback: 通过回调获取JdbcTemplate提供的CallableStatement,用户可以在该CallableStatement执行任何数量的操作; (四):结果集处理回调:通过回调处理ResultSet或将ResultSet转换为需要的形式 ①:RowMapper: 用于将结果集每行数据转换为需要的类型,用户需实现方法mapRow(ResultSet rs, int rowNum)来完成将每行数据转换为相应的类型。 ②:RowCallbackHandler: 用于处理ResultSet的每一行结果,用户需实现方法processRow(ResultSet rs)来完成处理,在该回调方法中无需执行rs.next(),
该操作由JdbcTemplate来执行,用户只需按行获取数据然后处理即可。 ③:ResultSetExtractor: 用于结果集数据提取,用户需实现方法extractData(ResultSet rs)来处理结果集,用户必须处理整个结果集;
2:搭建一个最简单的JdbcTemplate
<dependencies> <!--Spring核心包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.6.RELEASE</version> </dependency> <!--Spring的操作数据库坐标--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.6.RELEASE</version> </dependency> <!--Spring测试坐标--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.6.RELEASE</version> </dependency> <!--Mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency> <!--测试包--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>