Java框架spring 学习笔记(十八):事务管理(xml配置文件管理)

2023-05-09,,

在Java框架spring 学习笔记(十八):事务操作中,有一个问题:

 package cn.service;

 import cn.dao.OrderDao;

 public class OrderService {
private OrderDao orderDao; public void setOrderDao(OrderDao orderDao) {
this.orderDao = orderDao;
} //调用dao的方法
//业务逻辑层,写转账业务
public void accountMoney(){
//狗蛋转账给建国,在账面上看就是狗蛋减钱,建国多钱
//狗蛋减钱
orderDao.lessMoney();
//建国多钱
orderDao.moreMoney();
}
}

在转账过程中如果出现中断,比如狗蛋减完钱后中断了,那么账面上狗蛋减了1000元,建国却没有加上1000元。

当然不允许这样的情况发生,于是就需要使用事务管理对发生的错误操作进行回滚。

xml配置事务管理,修改bean.xml配置文件

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd "> <!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 注入dao对象 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="user" value="root"></property>
<property name="password" value="jqbjqbjqb123"></property>
</bean> <bean id="orderService" class="cn.service.OrderService">
<property name="orderDao" ref="orderDao"></property>
</bean>
<bean id="orderDao" class="cn.dao.OrderDao">
<!-- 注入jdbcTemplate对象-->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean> <!-- 创建jdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 把dataSource传递到模板对象中-->
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 第一步:配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 第二步:配置事务增强 -->
<tx:advice id="txadvice" transaction-manager="transactionManager">
<!-- 做事务操作 -->
<tx:attributes>
<!-- 设置进行事务操作的方法匹配规则-->
<!-- 星号通配符匹配account开头的所有方法-->
<tx:method name="account*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice> <!-- 第三步:配置切面 -->
<aop:config>
<!-- 切入点 -->
<aop:pointcut id="pointcut1" expression="execution(* cn.service.OrderService.*(..))"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1"/>
</aop:config>

之后发生错误时,会取消之前的对数据库的操作,保持数据的一致,保证数据的安全。

Java框架spring 学习笔记(十八):事务管理(xml配置文件管理)的相关教程结束。

《Java框架spring 学习笔记(十八):事务管理(xml配置文件管理).doc》

下载本文的Word格式文档,以方便收藏与打印。