天天看點

SpringDay05如何連接配接資料庫

導入spring的core,Aop,和資料庫持久層有關的架包

SpringDay05如何連接配接資料庫

在springd的JdbcDaoSupport的模闆類中有getJdbcTemplate方法擷取jdbcTemplate對象,通過jdbcTemplate對象對資料庫進行操作

操作流程

首先在com.web.base包下建立BaseDao類繼承JdbcDaoSupport,然後建立以下方法

@Resource(name="dataSource")
	public void setSuperDataSource(DataSource dataSource){
		super.setDataSource(dataSource);
	}
           

注入資料源實作JdbcTemplate的初始化

在dao層繼承baseDAO,通過getJdbcTemplate對資料庫進行操作

或者直接注入jdbcTemplate完成初始化

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-2.5.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

	<!-- 使用注解實作IOC -->
	<context:component-scan base-package="com.web" />

	<!-- 使用注解實作AOP -->
	<aop:aspectj-autoproxy />
	
	<!-- 配置資料源 -->
	<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
		<property name="username" value="scott"></property>
		<property name="password" value="123456"></property>
	</bean>
	
	<!-- 配置jdbcTemplate -->
	<!--  
	<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	-->
	
	<!--  
	<bean name="deptDAOImpl" class="com.web.dao.impl.DeptDAOImpl">
		<property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>
	-->
	
	<!--  
	<bean name="deptDAOImpl" class="com.web.dao.impl.DeptDAOImpl">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	-->
	
</beans>