Spring配置C3P0、Druid数据源和JdbcTemplate模板类
程序员文章站
2022-05-24 15:08:37
...
外部配置参数:jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///win668
jdbc.username=root
jdbc.password=root
Spring配置JdbcTemplate+c3p0数据源+Druid数据源
applicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--导入外部数据源配置参数-->
<context:property-placeholder location="jdbc.properties"/>
<!--配置c3p0数据源-->
<bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置druid数据源-->
<bean id="druid" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置tamplate模板-->
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="druid"></constructor-arg>
</bean>
</beans>
测试数据源
@Test
public void testDruid(){
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
DruidDataSource dataSource = app.getBean(DruidDataSource.class);
String s = dataSource.toString();
System.out.println(s);
}
@Test
public void testC3P0(){
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ComboPooledDataSource dataSource = (ComboPooledDataSource) app.getBean("c3p0");
System.out.println(dataSource);
}
测试模板类
@Test
public void testJdbcTemplate(){
//加载配置文件到Spring容器
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("spring_jdbc.xml");
//Spring容器通过JdbcTemplate.class 字节码创建 JdbcTemplate对象
JdbcTemplate template = app.getBean(JdbcTemplate.class);
//操作数据库
String sql="select * from user where id<?";
String sql1="select count(id) from user where id<?";
Integer integer = template.queryForObject(sql1, Integer.class, 5);
System.out.println(integer);
List<User> list = template.query(sql, new BeanPropertyRowMapper<User>(User.class), 5);
System.out.println(list);
System.out.println(template);
}