首先,我们创建3个java类,分别为TestC3p0,UserDao,UserService,要实现的目的:在UserService类中的add方法中调用UserDao的add方法,在UserDao中设置连接数据库的对象。在TestC3p0中进行测试。
package cn.itcast.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 stu value(?,?)";
int rows=jdbcTemplate.update(sql, "20","20");
System.out.println(rows);
}
}
package cn.itcast.c3p0;
public class UserService {
public UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void add() {
// System.out.println("service........");
userDao.add();
}
}
package cn.itcast.c3p0;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestC3p0 {
@Test
public void user() {
ApplicationContext context=new ClassPathXmlApplicationContext("bean2.xml");
UserService userService=(UserService) context.getBean("userService");
userService.add();
}
}
<?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 " >
<!-- 配置c3p0连接池 -->
<bean id="datesource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 注入属性 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///student"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 创建对象 -->
<bean id="userService" class="cn.itcast.c3p0.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="cn.itcast.c3p0.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!-- 创建JdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- <constructor-arg name="dataSource" ref="dataSource"></constructor-arg> -->
<property name="dataSource" ref="datesource"></property>
</bean>
</beans>
其中对象的创建都交给XML配置文件来实现,通过<bean>标签来完成。要完成上面的操作,需要连接数据库,导入Spring框架的jar包和c3p0的jar。