Spring中的JdbcTemplate
一、JdbcTemplate 概述
1.1 JdbcTemplate概述
它是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装,spring框架为我们提供了很多的操作模板类。
① 操作关系型数据的:
JdbcTemplate
HibernateTemplate
② 操作nosql数据库的:
RedisTemplate
③ 操作消息队列的:
JmsTemplate
1.2 JdbcTemplate 对象的创建
//我们可以参考一下他的源码
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
setDataSource(dataSource);
setLazyInit(lazyInit);
afterPropertiesSet();
}
//出了默认的构造函数之外,都需要提供一个数据源。
1.3 配置数据源
两种配置数据源的方式c3p0和DBCP。想要使用这两种数据源都需要导入对应的jar包。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置c3p0数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc://mysql:///spring_day02"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>