spring框架学习笔记7:事务管理及案例

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框架的学习就到这里

原文地址:https://www.cnblogs.com/xuyiqing/p/8465095.html

时间: 2024-08-08 18:55:32

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

Spring.Net学习笔记(7)-事务

一.开发环境 操作系统:Win7 编译器:VS2010 二.涉及程序集 Spring.Core.dll Spring.Data.dll Common.Logging.dll 三.开发过程 1.项目结构 2.IAccountDao.cs namespace Dao { public interface IAccountDao { void Create(string name, string userName); void Delete(string userName); } } 3.IUserD

Spring 框架基础(05):事务管理机制,和实现方式

本文源码:GitHub·点这里 || GitEE·点这里 一.Spring事务管理 1.基础描述 Spring事务管理的本质就是封装了数据库对事务支持的操作,使用JDBC的事务管理机制,就是利用java.sql.Connection对象完成对事务的提交和回滚. Connection conn = DriverManager.getConnection(); try { // 自动提交设置为false conn.setAutoCommit(false); // 执行增删改查操作 // 当操作成功后

spring框架学习笔记(二)

配置Bean Ioc容器 Ioc容器需要实例化以后才可以从Ioc容器里获取bean实例并使用. spring提供两种方式类型的Ioc容器实现: BeanFactory:底层的,面向spring框架的. ApplicationContext :面向开发人员的,一般用这个. 有两个实现类: ClassPathXmlApplicationContext:从类路径下加载配置文件. FileSystemXmlApplicationContext:从文件系统中加载配置文件. 两种方式配置文件是相同的. 通过

spring框架学习笔记4:SpringAOP实现原理

AOP AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善.OOP引入封装.继承.多态等概念来建立一种对象层次结构,用于模拟公共行为的一个集合.不过OOP允许开发者定义纵向的关系,但并不适合定义横向的关系,例如日志功能.日志代码往往横向地散布在所有对象层次中,而与它对应的对象的核心功能毫无关系对于其他类型的代码,如安全性.异常处理和透明的持续性也都是如此,这种散布在各

spring框架学习笔记(一)

仅为个人笔记,方便自己日后查看. eclipse安装spring插件的方法: http://jingyan.baidu.com/article/1612d5005fd087e20f1eee10.html 使用maven添加spring需要的jar包. 几个必须的jar包:core.bean.context.express.另外依赖一个日志包commons—logging pom.xml文件中为了统一版本,因此在properties写了版本号如下: <properties> <!-- sp

spring框架学习笔记(十)

通过注解的方式配置bean Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件. 即,想要实现注解的方式配置bean需要满足2个条件: 类上面标注特定组件,如:@Component.@Service.@Repository.@Controller 在配置文件中增加bean-scan:<context:component-scan base-package="com.pfSoft.annotation"></context:component

spring框架学习笔记(六)

bean的作用域 通过配置scope属性可以修改默认作用域如下: <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" scope="prototype"> 默认值是singleton,创建的是单例的bean实例,在Ioc容器初始化的时候bean对象已经构建成功.修改为prototpe则是为每一个bean创建一个新的实例. 使用外部属性文件 spring提供了一个PropertyP

spring框架学习笔记(三)

接上一节,配置bean的关联关系: 新增bean实体类Manufacture 代码如下: 其中要在Manufacture中包含对ProductEntity的引用. public class Manufacture { private String manName; private ProductEntity product; /** * * @return the manName */ public String getManName() { return manName; } /** * @p

Spring框架学习笔记(8)——AspectJ实现AOP

使用代理对象实现AOP虽然可以满足需求,但是较为复杂,而Spring提供一种简单的实现AOP的方法AspectJ 同样的计算器的DEMO 首先配置applicationContext.xml <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan> <!-- 配置自动为匹配 aspectJ 注