1 spring配置c3p0连接池
(1)导入jar包
(2) 创建spring配置文件,配置连接池
2、完整代码如下
UserDao.java
UserService.java
bean1.xml
ServiceTest.java 测试类
本文链接:https://liuyanzhao.com/5707.html
(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();
- }
- }
本文链接:https://liuyanzhao.com/5707.html
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏