8.事务

使用注解实现事务(声明式事务)
目标:通过事务 使以下方法 要么全成功、要么全失败
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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值