Spring提供了一套管理项目中的事务的机制

以前写过一篇简单的介绍事务的随笔:http://www.cnblogs.com/xuyiqing/p/8430214.html

还有一篇Hibernate的事务管理:http://www.cnblogs.com/xuyiqing/p/8449167.html

可以做个对比

Spring管理事务特有的属性:

事务传播行为:事务传播行为(propagation behavior)指的就是当一个事务方法被另一个事务方法调用时,这个事务方法应该如何进行。

例如:methodA事务方法调用methodB事务方法时,methodB是继续在调用者methodA的事务中运行呢,还是为自己开启一个新事务运行,这就是由methodB的事务传播行为决定的。

1、PROPAGATION_REQUIRED:如果当前没有事务,就创建一个新事务,如果当前存在事务,就加入该事务,该设置是最常用的设置

2、PROPAGATION_SUPPORTS:支持当前事务,如果当前存在事务,就加入该事务,如果当前不存在事务,就以非事务执行。‘

3、PROPAGATION_MANDATORY:支持当前事务,如果当前存在事务,就加入该事务,如果当前不存在事务,就抛出异常。

4、PROPAGATION_REQUIRES_NEW:创建新事务,无论当前存不存在事务,都创建新事务。

5、PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

6、PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。

7、PROPAGATION_NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作

接下来演示事务案例:简单模拟转账

需要的包:

新建一张表,放入数据:

package dao;

public interface AccountDao {

    //加钱
void increaseMoney(Integer id,Double money);
//减钱
void decreaseMoney(Integer id,Double money);
}
package dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao  {

    @Override
public void increaseMoney(Integer id, Double money) { getJdbcTemplate().update("update t_account set money = money+? where id = ? ", money,id); } @Override
public void decreaseMoney(Integer id, Double money) { getJdbcTemplate().update("update t_account set money = money-? where id = ? ", money,id);
} }
package service;

public interface AccountService {

    //转账方法
void transfer(Integer from,Integer to,Double money); }
package service;

import dao.AccountDao;

public class AccountServiceImpl implements AccountService {

    private AccountDao ad;

    @Override
public void transfer(final Integer from, final Integer to, final Double money) {
// 减钱
ad.decreaseMoney(from, money);
// 加钱
ad.increaseMoney(to, money);
} public void setAd(AccountDao ad) {
this.ad = ad;
} }
package tx;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import service.AccountService; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name="accountService")
private AccountService as; @Test
public void fun1(){ as.transfer(1, 2, 100d); }
}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" /> <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<!-- 以方法为单位,指定方法应用什么事务属性
isolation:隔离级别
propagation:传播行为
read-only:是否只读
其他方法的配置没有用到,但它们通常是统一配置
-->
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" /> <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
</tx:attributes>
</tx:advice> <!-- 配置织入 -->
<aop:config >
<!-- 配置切点表达式 -->
<aop:pointcut expression="execution(* service.*ServiceImpl.*(..))" id="txPc"/>
<!-- 配置切面 : 通知+切点
advice-ref:通知的名称
pointcut-ref:切点的名称
-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
</aop:config> <!-- 1.将连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
<property name="driverClass" value="${jdbc.driverClass}" ></property>
<property name="user" value="${jdbc.user}" ></property>
<property name="password" value="${jdbc.password}" ></property>
</bean> <!-- 2.Dao-->
<bean name="accountDao" class="dao.AccountDaoImpl" >
<property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 3.Service-->
<bean name="accountService" class="service.AccountServiceImpl" >
<property name="ad" ref="accountDao" ></property>
</bean> </beans>

db.properties

jdbc.jdbcUrl=jdbc:mysql:///mybase
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=xuyiqing

运行Demo后结果:

转账成功!

补充:

可以采用注解方式代替XML配置文件:

配置文件只要一行即可:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" /> <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
<property name="transactionManager" ref="transactionManager" ></property>
</bean> <!-- 开启使用注解管理aop事务 -->
<tx:annotation-driven/> <!-- 1.将连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
<property name="driverClass" value="${jdbc.driverClass}" ></property>
<property name="user" value="${jdbc.user}" ></property>
<property name="password" value="${jdbc.password}" ></property>
</bean> <!-- 2.Dao-->
<bean name="accountDao" class="dao.AccountDaoImpl" >
<property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 3.Service-->
<bean name="accountService" class="service.AccountServiceImpl" >
<property name="ad" ref="accountDao" ></property>
</bean> </beans>
package service;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import dao.AccountDao; @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)
public class AccountServiceImpl implements AccountService { private AccountDao ad; @Override
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)
public void transfer(final Integer from, final Integer to, final Double money) {
// 减钱
ad.decreaseMoney(from, money);
// 加钱
ad.increaseMoney(to, money);
} public void setAd(AccountDao ad) {
this.ad = ad;
} }

测试后同样成功!

Spring框架的学习就到这里

spring框架学习笔记7:事务管理及案例的更多相关文章

  1. Spring框架学习笔记(1)

    Spring 框架学习笔记(1) 一.简介 Rod Johnson(spring之父) Spring是分层的Java SE/EE应用 full-stack(服务端的全栈)轻量级(跟EJB比)开源框架, ...

  2. Spring框架学习笔记(5)——Spring Boot创建与使用

    Spring Boot可以更为方便地搭建一个Web系统,之后服务器上部署也较为方便 创建Spring boot项目 1. 使用IDEA创建项目 2. 修改groupid和artifact 3. 一路n ...

  3. Spring框架学习笔记(8)——spring boot+mybatis plus+mysql项目环境搭建

    之前写的那篇Spring框架学习笔记(5)--Spring Boot创建与使用,发现有多小细节没有提及,,正好现在又学习了mybatis plus这款框架,打算重新整理一遍,并将细节说清楚 1.通过I ...

  4. Spring框架学习笔记(10)——Spring中的事务管理

    什么是事务 举例:A给B转500,两个动作,A的账户少500,B的账户多500 事务就是一系列的动作, 它们被当做一个单独的工作单元. 这些动作要么全部完成, 要么全部不起作用 一.注解添加事务管理方 ...

  5. 深入学习Spring框架(四)- 事务管理

    1.什么是事务? 事务(Transaction)是一个操作序列.这些操作要么都做,要么都不做,是一个不可分割的工作单位,是数据库环境中的逻辑工作单位.事务是为了保证数据库的完整性.例如:A给B转账,需 ...

  6. 手写Spring框架学习笔记

    以下是咕泡公开课的学习笔记 一.创建工程springdemo 二.在pom中配置servlet <dependency> <groupId>javax.servlet</ ...

  7. Spring框架学习笔记(3)——SpringMVC框架

    SpringMVC框架是基于Spring框架,可以让我们更为方便的进行Web的开发,实现前后端分离 思路和原理 我们之前仿照SpringMVC定义了一个自定义MVC框架,两者的思路其实都是一样的. 建 ...

  8. Spring框架学习笔记(4)——SSM整合以及创建Maven自定义模版

    Spring+Spring MVC+MyBatis+Maven SSM整合的核心还是Spring+MyBatis的整合,回顾一下MyBatis操作数据库流程,我们是使用一个SQLSessionFact ...

  9. spring框架学习笔记1:搭建测试

    Spring框架介绍: Spring框架涵盖了web.service.dao三层,本身是一个存放对象的容器 形象来说:Spring是项目中对象管家 Spring框架的两大核心思想:控制反转(IOC). ...

随机推荐

  1. (转)2018CRM系统最新排行榜

    https://www.jianshu.com/p/718cc29de91f 2018CRM系统最新排行榜 深谷幽兰呼 关注 2018.09.04 10:22 字数 1524 阅读 3182评论 0喜 ...

  2. jQuery之必会增删改查Dom操作

    .next  .prev <button>change</button> <span class = '.demo'>aaa</span> <p ...

  3. react-native 新手爬坑经历(Could not connect to development server.)

    来,先说下报错出现场景,刚跑完项目加载完是好的,但是双击R后就开始耍小脾气了-红屏出现,如下图 首先检查包服务器是否运行正常.在项目文件夹下输入react-native start或者npm star ...

  4. python学习笔记(七)- 递归、python内置函数、random模块

    1.函数的不固定参数: #参数不是必填的.没有限制参数的个数.返回参数组的元组 def syz(*args): #参数组,不限制参数个数 #‘args’参数的名字可以随便命名 print(args) ...

  5. Shell脚本中"command not found"报错处理

    字符串的定义与赋值 # 定义STR1变量,值为abc STR1 = "abc"(错误写法) STR1="abc"(正确写法) 在编写java代码时会考虑到格式化 ...

  6. 【转载】SQL Server - 使用 Merge 语句实现表数据之间的对比同步

    原文地址:SQL Server - 使用 Merge 语句实现表数据之间的对比同步 表数据之间的同步有很多种实现方式,比如删除然后重新 INSERT,或者写一些其它的分支条件判断再加以 INSERT ...

  7. Python Day 3

    阅读目录: 内容回顾: 变量(标识符)的命名规范: 常量: 格式化输入\输出: 注释: 基本数据类型: 运算符: ##内容回顾 1.语言的分类: -- 机器语言:直接编写0,1指令,直接能被硬件执行. ...

  8. Xpath在选择器中正确,在代码中返回的是空列表问题

    一.问题: 在进行爬虫的时候我们会用到xpath解析html文件,但是会有一种情况就是在xpath选择器中可以使用,但是在代码中就无法使用的情况. 二.原因: 1.是元素中有tbody的原因,这个元素 ...

  9. S 实现精确加减乘除

    //加法函数 function accAdd(arg1, arg2) { var r1, r2, m; try { r1 = arg1.toString().split(".")[ ...

  10. mysql 地理位置定位

    SET @pt2 = ST_GeomFromText('POINT(116.405289 39.904987)'); SELECT *,ST_Distance_Sphere(ST_GeomFromTe ...