1.直接使用JDBCTemplate
A.手动实例化数据源
B.手动实例化JdbcTemplate
Spring环境下,所有的JavaBean都应该交给IOC容器进行管理。
那就意味着DataSource的初始化以及为DAO层注入DataSource都需要通过容器来完成
要求要在DAO增使用JdbcTemplate必须继承:JdbcDAOSupport系列的基础类。
2.集成Spring DAO
A.在Spring配置文件中配置数据源
<!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/wei"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
B.编写DAO继承JdbcDaoSupport
public class PersonDAO2 extends JdbcDaoSupport{
@Test
public void queryList() {
List<Person> queryForList = this.getJdbcTemplate().query("select * from person where 1 = ?", new RowMapper<Person>() {
@Override
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
int personId = rs.getInt("personId");
String personName = rs.getString("personName");
Person person = new Person(personId,personName);
return person;
}
},new String[] {"1"});
for (Person person : queryForList) {
System.out.println("所有数据:"+person);
}
}
}
C.为dao注入数据源
<bean id="personDAO2" class="cn.wang.dao.PersonDAO2">
<!-- 为dao注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
3.优化集成的SpringDAO
3.1:为每个dao注入数据源代码冗余,抽取出dao的父类,让其继承JdbcDaoSupport。
只为父类注入DataSource即可。考虑到JdbcDaoSupport的setDataSupport方法是final修饰的,
所有在dao的自定义父类中,需重新定义setDataSource系列的方法,调用JdbcDaoSupport的setDataSource的方法!
public class BasePersonDAO extends JdbcDaoSupport{
@Resource
public void setDataSource2(DataSource dataSource) {
super.setDataSource(dataSource);
}
}
3.2使用内部的属性文件存储连接池的配置信息(也可以使用外部属性文件)
<!-- 配置c3p0的连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/wei"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<property name="minPoolSize" value="1"></property>
<property name="maxPoolSize" value="5"></property>
<property name="maxIdleTime" value="2000"></property>
</bean>
3.3测试
@Repository
@Scope("prototype")
public class TestPersonDAO2 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext_base.xml");
PersonDAO2 bean = ac.getBean(PersonDAO2.class);
bean.queryList();
}
}