spring配置c3p0连接池
Spring 配置连接池和dao使用jdbcTemplate
1 spring配置c3p0连接池
第一步 导入jar包
第二步 创建spring配置文件,配置连接池
(1)把代码在文件配置中进行配置
2 dao使用jdbcTemplate
(1)创建service和dao,配置service和dao对象,在service注入dao对象
具体代码: 演示一遍c3p0添加数据操作
bean3.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<!-- 开启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:///news"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 创建service和dao对象, 在service注入dao对象 -->
<bean id="userService" class="com.cn.c3p0.UserService">
<!-- 注入dao对象 -->
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.cn.c3p0.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!-- 创建jdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
UserDao.java
package com.cn.c3p0;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDao {
private JdbcTemplate jdbcTemplate;
//得到JdbcTemplate对象
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
//添加操作
public void add() {
// TODO Auto-generated method stub
String sql="insert into my value(?,?)";
jdbcTemplate.update(sql, "张悦", "520");
}
}
UserService.java
package com.cn.c3p0;
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void add(){
userDao.add();
}
}
TestService.java
package com.cn.c3p0;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestService {
@Test
public void testDemo(){
ApplicationContext context=
new ClassPathXmlApplicationContext("bean3.xml");
UserService service=(UserService) context.getBean("userService");
service.add();
}
}