【sping揭秘】19、关于spring中jdbctemplate中的DataSource怎么来呢
我们这是可以正好借助之前学的factorybean类,自己吧jdbctemplate加载到spring容器中,我们可以封装多个这种对象,那么可以实现针对不同的数据库的jdbctemplate
首先我们肯定要引入对应的jar,来构建数据源对象
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-dbcp2</artifactId><version>2.1.1</version></dependency>
根据这个我们简单的创建一个jdbctemplate对象
package cn.cutter.start.bean;import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.beans.factory.FactoryBean; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component;/*** 用来封装第三方对象的类,加入spring容器* @author xiaof**/ @Component public class JdbcTemplateFactoryTestBean implements FactoryBean<JdbcTemplate> {@Overridepublic JdbcTemplate getObject() throws Exception {BasicDataSource dataSource = new BasicDataSource();//设置相应的参数//1、数据库驱动类dataSource.setDriverClassName("com.mysql.jdbc.Driver");//2、url,用户名,密码dataSource.setUrl("jdbc:mysql://localhost:3306/liferay?characterEncoding=utf-8");dataSource.setUsername("liferay"); dataSource.setPassword("xiaofeng2017");//3、初始化连接大小dataSource.setInitialSize(1);//4、连接池最大数据量dataSource.setMaxTotal(500);//5、连接池最大小空闲dataSource.setMinIdle(1);dataSource.setMaxIdle(20);//6、最大等待时间 单位毫秒dataSource.setMaxWaitMillis(20 * 1000);//7、指明连接是否被空闲连接回收器(如果有)进行检验dataSource.setPoolPreparedStatements(true);//8、运行一次空闲连接回收器的时间间隔(60秒)dataSource.setTimeBetweenEvictionRunsMillis(60 * 1000);//9、验证时使用的SQL语句dataSource.setValidationQuery("SELECT 1 FROM DUAL");//10、借出连接时不要测试,否则很影响性能//11、申请连接的时候检测,如果空闲时间大于 timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效dataSource.setTestWhileIdle(false);JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);return jdbcTemplate;}@Overridepublic Class<?> getObjectType() {return JdbcTemplate.class;}}
好了,测试一下
@Testpublic void testJdbcTemplate() {ApplicationContext ctx = this.before();JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplateFactoryTestBean"); // Object obj = (IntroductionTestBean) ctx.getBean("introductionTestBean");//执行sqlString sql = "select 1 from dual";String sql2 = "update xiaof_foo t set t.userName = ?, t.modifiedDate = ? where t.fooid = ? ";// jdbcTemplate.execute(sql); jdbcTemplate.update(sql2, "cutter_point", new Date(), "1");}
Jdbctemplate
创建jdbctemplate只要创建对应的DataSource就可以了,至于其他查询,多种多样
NamedParameterJdbcTemplate
我们在使用jdbctemplate的时候,都是通过?来指定对应的参数,那么这里就有一种更加贴近语义的方式
我们创建这个template对象
package cn.cutter.start.bean;import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.beans.factory.FactoryBean; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Component;/*** 加入spring容器,使用 NamedParameterJdbcTemplate* @author xiaof**/ @Component public class NamedParameterJdbcTemplateTestFactoryBean implements FactoryBean<NamedParameterJdbcTemplate> {@Overridepublic NamedParameterJdbcTemplate getObject() throws Exception {BasicDataSource dataSource = new BasicDataSource();//设置相应的参数//1、数据库驱动类dataSource.setDriverClassName("com.mysql.jdbc.Driver");//2、url,用户名,密码dataSource.setUrl("jdbc:mysql://localhost:3306/liferay?characterEncoding=utf-8");dataSource.setUsername("liferay"); dataSource.setPassword("xiaofeng2017");//3、初始化连接大小dataSource.setInitialSize(1);//4、连接池最大数据量dataSource.setMaxTotal(500);//5、连接池最大小空闲dataSource.setMinIdle(1);dataSource.setMaxIdle(20);//6、最大等待时间 单位毫秒dataSource.setMaxWaitMillis(20 * 1000);//7、指明连接是否被空闲连接回收器(如果有)进行检验dataSource.setPoolPreparedStatements(true);//8、运行一次空闲连接回收器的时间间隔(60秒)dataSource.setTimeBetweenEvictionRunsMillis(60 * 1000);//9、验证时使用的SQL语句dataSource.setValidationQuery("SELECT 1 FROM DUAL");//10、借出连接时不要测试,否则很影响性能//11、申请连接的时候检测,如果空闲时间大于 timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效dataSource.setTestWhileIdle(false);NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);return namedParameterJdbcTemplate;}@Overridepublic Class<?> getObjectType() {// TODO Auto-generated method stubreturn NamedParameterJdbcTemplate.class;}}
使用这个,我们来查询一下数据库的数据量
数据库中我们查询结果
select count(*) from xiaof_foo t where t.fooId = '1'
代码中使用NamedParameterJdbcTemplate
@Testpublic void testNamedParameterJdbcTemplate() {ApplicationContext ctx = this.before();NamedParameterJdbcTemplate namedParameterJdbcTemplate = (NamedParameterJdbcTemplate) ctx.getBean("namedParameterJdbcTemplateTestFactoryBean"); // Object obj = (IntroductionTestBean) ctx.getBean("introductionTestBean");//执行sql//设置参数对象SqlParameterSource sqlParameterSource = new MapSqlParameterSource("fooId", "1");//统计个数String sql = "select count(*) from xiaof_foo t where t.fooId = :fooId";int count = namedParameterJdbcTemplate.queryForObject(sql, sqlParameterSource, Integer.class);System.out.println("个数是:" + count);}
还有哦,最后注意下,这个 :参数名 这个是区分大小写的
如果有多个参数,那么直接对map对象进行put就可以了
@Testpublic void testNamedParameterJdbcTemplate() {ApplicationContext ctx = this.before();NamedParameterJdbcTemplate namedParameterJdbcTemplate = (NamedParameterJdbcTemplate) ctx.getBean("namedParameterJdbcTemplateTestFactoryBean"); // Object obj = (IntroductionTestBean) ctx.getBean("introductionTestBean");//执行sql//设置参数对象MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource("fooid", "1");sqlParameterSource.addValue("userName", "cutter_point");//统计个数String sql = "select count(*) from xiaof_foo t where t.fooId = :fooid and userName = :userName";int count = namedParameterJdbcTemplate.queryForObject(sql, sqlParameterSource, Integer.class);System.out.println("个数是:" + count);}
结果:
借助bean对象进行传参
@Testpublic void testNamedParameterJdbcTemplateModel() {ApplicationContext ctx = this.before();NamedParameterJdbcTemplate namedParameterJdbcTemplate = (NamedParameterJdbcTemplate) ctx.getBean("namedParameterJdbcTemplateTestFactoryBean"); // Object obj = (IntroductionTestBean) ctx.getBean("introductionTestBean"); String sql = "select * from xiaof_foo t where t.fooId = :fooId";XiaoFFoo xiaoFFoo = new XiaoFFoo();xiaoFFoo.setFooId(1l);SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(xiaoFFoo);List<Map<String, Object>> xiaoFFoo2s = namedParameterJdbcTemplate.queryForList(sql, sqlParameterSource);System.out.println("名字是:" + xiaoFFoo2s.get(0).get("userName"));}
SimpleJdbcTemplate
集jdbctemplate和namedparameterJdbctemplate 与一身,并在两者基础上新增java 5的特性:
动态参数
自动拆箱解箱
范型
不过这个在后面的spring中会被去除,既然这样,我们就不浪费时间再这个上面了,拜拜呢你嘞。。。
转载于:https://www.cnblogs.com/cutter-point/p/9147745.html
【sping揭秘】19、关于spring中jdbctemplate中的DataSource怎么来呢相关推荐
- Spring中JdbcTemplate中使用RowMapper
转自:https://blog.csdn.net/u012661010/article/details/70049633 1 sping中的RowMapper可以将数据中的每一行数据封装成用户定义的类 ...
- Spring中jdbcTemplate的用法实例
一.首先配置JdbcTemplate: 要使用Jdbctemplate 对象来完成jdbc 操作.通常情况下,有三种种方式得到JdbcTemplate 对象. 第一种方式:我们可以在自己 ...
- SSM-Spring-19:Spring中JdbcTemplate
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- Spring自带一个ORM持久化框架JdbcTemplate,他可以说是jdbc的加强版,但是对最细微的控制肯 ...
- Spring 学习 day3 : AOP,Spring中JdbcTemplate的使用
1.AOP 1.1 什么是AOP 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方 式和运行期动态代理实现程序功能的统一维护的一种技术. ...
- JdbcTemplate在Spring的ioc中使用
bean.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http ...
- 在Spring Boot测试中使用Testcontainer进行数据库集成测试
在此博客文章中,我想演示如何在Spring Boot测试中集成Testcontainer以便与数据库一起运行集成测试. 我没有使用Testcontainers的Spring Boot模块. 如何与他们 ...
- Spring在SSH中的角色和作用
一直搞不清在ssh中 struts和spring分别担任什么样的角色 总觉得它们都是mvc框架.别人告诉说,Struts是纯MVC框架,spring 只是有一个组件是MVC.搜到了下面一篇文章,对我的 ...
- Spring Boot 应用中 Spring Session 的配置(1) : 自动配置 SessionAutoConfiguration
概述 本文基于以下组合的应用,通过源代码分析一下一个Spring Boot应用中Spring Session的配置过程: Spring Boot 2.1.3.RELEASE Spring Sessio ...
- java注解返回不同消息,Spring MVC Controller中的一个读入和返回都是JSON的方法如何获取javax.validation注解的异常信息...
Spring MVC Controller中的一个读入和返回都是JSON的方法怎么获取javax.validation注解的错误信息? 本帖最后由 LonelyCoder2012 于 2014-03- ...
最新文章
- SQLite中SELECT基本形式
- JavaScript学习13 JavaScript中的继承
- Linux shell的和||
- HDFS分布式文件系统设计原理
- Eclipse设置:背景与字体大小和xml文件中字体大小调整
- linux清空输入框,Linux uniq 命令
- Java编译器调试不了_使用Maven设置Java编译器的-source和-target-不起作用
- Android仿人人客户端(v5.7.1)——网络模块处理的架构
- Jdk1.6 JUC源码解析(12)-ArrayBlockingQueue
- 非参数统计:方法与应用(全书例题R语言实现)
- 中国地图全图 中国卫星地图 谷歌地图高清卫星地图
- Java方法的重载和重写
- Python: PS 滤镜--碎片特效
- bzoj-4565-区间dp+状压
- Python 第三方模块 科学计算 SciPy模块4 线性代数1
- 世界上最著名也最危险的APT恶意软件清单
- 第二十九章 管理许可(二)
- MPP(大规模并行处理)简介
- java操作跨页的word cell_Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行...
- js设计模式——组合模式
热门文章
- logistic模型原理与推导过程分析(1)
- Koa框架——coderhub实战
- 四、MyBatis 框架 Dao 动态代理
- LeetCode 2114. 句子中的最多单词数
- 牛客 数学实验(模拟)
- LeetCode 1198. 找出所有行中最小公共元素(二分/合并有序链表)
- LeetCode 538. 把二叉搜索树转换为累加树(逆中序 根右左)
- python获取股票数据_python根据股票代码获取当前数据
- 什么是spring_Spring 源码第三弹!EntityResolver 是个什么鬼?
- python暂停和恢复_python – 暂停和恢复QThread