1 spring 配置 c3p0 连接池
(1)导入 jar 包
(2) 创建 spring 配置文件,配置连接池
2、完整代码如下
UserDao.java
- package com.liuyanzhao.c3p0;
- import org.springframework.jdbc.core.JdbcTemplate;
- public class UserDao {
- //得到 JdbcTemplate 对象
- private JdbcTemplate jdbcTemplate;
- public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
- this.jdbcTemplate = jdbcTemplate;
- }
- //添加操作
- public void add() {
- String sql = “insert into user value(?,?,?)”;
- jdbcTemplate.update(sql,6,“刘言曌”,“123456”);
- }
- }
UserService.java
- package com.liuyanzhao.c3p0;
- public class UserService {
- //添加操作
- private UserDao userDao;
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- public void add() {
- userDao.add();
- }
- }
bean1.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://127.0.0.1:3306/spring?useUnicode=true&characterEncoding=utf8”></property>
- <property name=“user” value=“root”></property>
- <property name=“password” value=“”></property>
- </bean>
- <bean id=“userServiceId” class=“com.liuyanzhao.c3p0.UserService”>
- <!–注入 dao 对象–>
- <property name=“userDao” ref=“userDaoId”></property>
- </bean>
- <bean id=“userDaoId” class=“com.liuyanzhao.c3p0.UserDao”>
- <!–注入 jdbcTemplate 对象–>
- <property name=“jdbcTemplate” ref=“jdbcTemplateId”></property>
- </bean>
- <!–创建 jdbcTemplate 对象–>
- <bean name=“jdbcTemplateId” class=“org.springframework.jdbc.core.JdbcTemplate”>
- <!–把 dataSource 传递到模板里面–>
- <property name=“dataSource” ref=“dataSource”></property>
- </bean>
- </beans>
ServiceTest.java 测试类
- package com.liuyanzhao.c3p0;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class ServiceTest {
- @Test
- public void test() {
- ApplicationContext context =
- new ClassPathXmlApplicationContext(“bean1.xml”);
- UserService userService = (UserService) context.getBean(“userServiceId”);
- userService.add();
- }
- }