Spring与数据库
Spring与jdbc
引入dataSource
在客户端
模板编程
类的结构图, 真正干活的是JdbcTemplate(底层实现,操作 excute方法)
JdbcTemplate 构造函数 有DataSource参数 继承JdbcAccessor抽象类 抽象类有方法setDataSource(DataSource)
JdbcDaoSupport 抽象类 (不能被实例化 只能用来继承) 有setDataSource ,setDataSource创建了JdbcTemplate对象,DataSource最终赋值给了 JdbcTemplate
有setTemplate方法
JdbcAccessor抽象类 方法setDataSource(DataSource)
方案一
继承JdbcDaoSupport 两种选择 1.注入DataSource 2.注入JdbcTemplate
1.注入DataSource(setDataSource), 执行 利用JdbcDaoSupport getJdbcTemplate 执行JdbcTemplate的excute方法
2注入JdbcTemplate(JdbcSupport有setDatasource方法) 建立jdbcTemplate bean,注入DataSource(继承自JdbcAccesor的setDataSource方法)
方案二
继承Jdbctemplate 注入(1.JdbcTemplate继承JdbcAccessor 的 setDataSourc 2.利用JdbcTemplate本身构造器) , 执行利用 JdbcTemplate excute方法
1.
2.
方案三
私有属性 JdbcTemplate ,提供set方法 注入,执行 this.jdbTemplate.excute
spring与jdbc的查询
原Jdbc查询操作
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 按照指定的路径加载配置文件 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:jdbc.properties</value> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <bean id="studentDao1_1" class="com.itheima09.spring.jdbc.dao.StudentDao1"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <bean id="studentDao1_2" class="com.itheima09.spring.jdbc.dao.StudentDao1"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate"/> </property> </bean> <bean id="studentDao2_1" class="com.itheima09.spring.jdbc.dao.StudentDao2"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <bean id="studentDao2_2" class="com.itheima09.spring.jdbc.dao.StudentDao2"> <constructor-arg index="0" ref="dataSource"></constructor-arg> </bean> <bean id="studentDao3" class="com.itheima09.spring.jdbc.dao.StudentDao3"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate"/> </property> </bean> </beans>
@Test public void testStuent() throws Exception{ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-jdbc.xml"); StudentDao3 studentDao3=(StudentDao3)context.getBean("studentDao3"); studentDao3.queryStudent(); }
Spring的声明式事务处理
概念
程序员不再负责处理事务,事务处理交给spring容器来做。
具体的详解
程序员负责两个内容:
1、 对表的crud操作:目标类的目标方法
2、 告诉spring容器什么样的目标方法采用什么样的事务策略
Spring容器负责:(切面)
负责事务的处理
实现原理
采用了aop技术来实现的。