Spring学习笔记五 JDBC DAO

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();
		}
	}	
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值