使用注解实现事务(声明式事务)
目标:通过事务 使以下方法 要么全成功、要么全失败
public void addStudent() {
// 增加班级
// 增加学生
// CRUD
}
1.所需要的jar包
(1)spring-tx-4.3.9.RELEASE.jar
事务所需的jar包
(2)commons-dbcp-1.4.jar
连接池使用到的数据源
(3)commons-pool-1.6.jar
连接池
(4)ojdbc7.jar
事务与数据库相关,所以需要连接数据库
(5)spring-jdbc-4.3.9.RELEASE.jar
(6)aopalliance-1.0.jar
事务依赖于aop
2.配置
jdbc\mybatis\spring
增加事务tx的命名空间
<tx:annotation-driven transaction-manager=“transactionManager” />
<?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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置数据库相关事务 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:ORCL"></property>
<property name="username" value="scott"></property>
<property name="password" value="tiger"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="10"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 增加对事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="studentDao" class="nuc.hzb.dao.impl.StudentDaoImpl"></bean>
<bean id="studentService" class="nuc.hzb.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
</beans>
3.使用
<bean id="studentDao" class="nuc.hzb.dao.impl.StudentDaoImpl"></bean>
<bean id="studentService" class="nuc.hzb.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
将需要成为事务的方法前增加注解:
@Transactional(readOnly = false, propagation = Propagation.REQUIRED,
rollbackFor = {SQLException.class, ArithmeticException.class})
// 要么全成功,要么全失败
// rollbackFor:如果出现后面的异常,则回滚
@Override
public void addStudent(Student student) {
// TODO Auto-generated method stub
studentDao.addStudent(student);
}