【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> { @Override
public 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;
} @Override
public Class<?> getObjectType() {
return JdbcTemplate.class;
} }
好了,测试一下
@Test
public void testJdbcTemplate() {
ApplicationContext ctx = this.before(); JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplateFactoryTestBean");
// Object obj = (IntroductionTestBean) ctx.getBean("introductionTestBean"); //执行sql
String 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> { @Override
public 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;
} @Override
public Class<?> getObjectType() {
// TODO Auto-generated method stub
return NamedParameterJdbcTemplate.class;
} }
使用这个,我们来查询一下数据库的数据量
数据库中我们查询结果
select count(*) from xiaof_foo t where t.fooId = '1'

代码中使用NamedParameterJdbcTemplate
@Test
public 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就可以了
@Test
public 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对象进行传参
@Test
public 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中会被去除,既然这样,我们就不浪费时间再这个上面了,拜拜呢你嘞。。。
【sping揭秘】19、关于spring中jdbctemplate中的DataSource怎么来呢的更多相关文章
- Spring中JdbcTemplate中使用RowMapper
转自:https://blog.csdn.net/u012661010/article/details/70049633 1 sping中的RowMapper可以将数据中的每一行数据封装成用户定义的类 ...
- Spring之JDBCTemplate学习
一.Spring对不同的持久化支持: Spring为各种支持的持久化技术,都提供了简单操作的模板和回调 ORM持久化技术 模板类 JDBC org.springframework.jdbc.core. ...
- Spring中JdbcTemplate的基础用法
Spring中JdbcTemplate的基础用法 1.在DAO中使用JdbcTemplate 一般都是在DAO类中使用JdbcTimplate,在XML配置文件中配置好后,可以在DAO中注入即可. 在 ...
- Spring 中jdbcTemplate 实现执行多条sql语句
说一下Spring框架中使用jdbcTemplate实现多条sql语句的执行: 很多情况下我们需要处理一件事情的时候需要对多个表执行多个sql语句,比如淘宝下单时,我们确认付款时要对自己银行账户的表里 ...
- SSM-Spring-19:Spring中JdbcTemplate
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- Spring自带一个ORM持久化框架JdbcTemplate,他可以说是jdbc的加强版,但是对最细微的控制肯 ...
- 2018.12.25 Spring中JDBCTemplate模版API学习
1 Spring整合JDBC模版 1.1 spring中土拱了一个可以操作数据库的对象.对象封装了jdbc技术 JDBCTemplateJDBC模板对象 1.2 与DBUtils中的QueryRunn ...
- Spring中JDBCTemplate的入门
Spring是IOC和AOP的容器框架,一站式的框架 连接数据库的步骤:[必须会写] Spring当中如何配置连接数据库? 第一步配置核心配置文件: <?xml version="1. ...
- Spring中jdbcTemplate的用法实例
一.首先配置JdbcTemplate: 要使用Jdbctemplate 对象来完成jdbc 操作.通常情况下,有三种种方式得到JdbcTemplate 对象. 第一种方式:我们可以在自己定 ...
- spring JdbcTemplate在spring的ioc中使用
package com.com.jdbctemplate; import org.springframework.context.ApplicationContext; import org.spri ...
随机推荐
- Mysql 关键字
ADD ALL ALTER ANALYZE AND AS ASC ASENSITIVE BEFORE BETWEEN BIGINT BINARY BLOB BOTH BY CALL CASCADE C ...
- I/O系统(一)
输入输出系统的发展大致可以分为4个阶段1.早期阶段 特点: 1.1每个IO设备都得有一套独立的逻辑电路和CPU相连. 1.2输入输出过程需要通过CPU,穿插在程序运行的过程中,处理IO时候 ...
- fortitoken
1.token状态为error,且不能分配给用户使用 解决: 关联有User的token状态是error的原因是:用户一直并未使用.
- 442. Find All Duplicates in an Array找出数组中所有重复了两次的元素
[抄题]: Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and o ...
- Spring MVC中@JsonView的使用
一.@JsonView注解的简介 @JsonView是jackson json中的一个注解,Spring webmvc也支持这个注解,它的作用就是控制输入输出后的json 二.@JsonView注解的 ...
- dbus 消息和消息总线实例讲解-一
应用程序A和消息总线连接,这个连接获取了一个众所周知的公共名(记作连接A).应用程序A中有对象A1提供了接口I1,接口I1有方法M1. 应用程序B和消息总线连接,要求调用连接A上对象A1的接口I1的方 ...
- SSM三大框架整合
三大框架整合的思路 1.Dao层: Mybatis的配置文件:SqlMapConfig.xml 不需要配置任何内容,需要有文件头.文件必须存在. applicationContext-dao.xml: ...
- Web 研发模式的演变
前不久徐飞写了一篇很好的文章:Web 应用的组件化开发.本文尝试从历史发展角度,说说各种研发模式的优劣. 一.简单明快的早期时代 可称之为 Web 1.0 时代,非常适合创业型小项目,不分前后端,经常 ...
- playframework 一步一步来 之 日志 (二)
带着之前的疑问,我们先回顾一下日志相关的知识: 首先是SL4J,SL4J是个什么东西来着?官方解释为:“The Simple Logging Facade for Java (SLF4J) serve ...
- 第34 memcached缓存
1.缓存数据库 缓存:将数据存储在内存中,只有当磁盘胜任不了的时候,才会启用缓存. 缺点:断电数据丢失(双电),用缓存存储数据的目的只是为了应付大并发的业务,至于数据存储及可靠性不要找他了. 数据 ...