美文网首页
spring事务用法

spring事务用法

作者: sunpy | 来源:发表于2019-03-24 16:28 被阅读0次

Spring事务传播范围

propagation="REQUIRED"
如果方法运行时,已经处于一个事务之中,那么直接就加入当前事务中,如果没有,那么就创建一个新的事务。
propagation="REQUIRES_NEW
不管是否存在新的活动事务,都将会开启一个新的事务。如果一个方法运行多个事务,如果方法运行当前的事务中,那么原事务将挂起。
propagation="NESTED"
支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。
propagation="SUPPORTS"
让当前的方法在一个事务中工作,否则方法在没有任务事务的情况下工作。
propagation="NOT_SUPPORTED"
当调用方法时,如果存在一个活动事务,那么该活动事务将被暂停,直到方法调用结束为止。
propagation="NEVER"
当调用方法时,如果系统中存在一个活动事务且发生错误,那么必须在系统中没有任何活动事务的情况下调用方法。
propagation="MANDATORY"
当调用方法时,如果系统中不存在一个活动事务且发生了错误,必须确保在访问该方法时已经创建了一个事务。

入门例子

表设计:name字段不可以为NULL

CREATE TABLE `single_user` (
  `id` bigint(18) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(18) NOT NULL,
  `age` int(3) DEFAULT NULL,
  `pwd` varchar(32) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `modify_time` datetime DEFAULT NULL,
  `deleted` tinyint(4) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3695758 DEFAULT CHARSET=utf8;

CREATE TABLE `single_vip` (
  `vip_id` bigint(18) unsigned NOT NULL AUTO_INCREMENT,
  `vip_name` varchar(18) NOT NULL,
  `vip_create_time` datetime NOT NULL,
  PRIMARY KEY (`vip_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<!-- 配置Druid数据库连接池 -->
<beans:bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <beans:property name="driverClassName" value="${jdbc_driverClass}"></beans:property> 
    <beans:property name="url" value="${jdbc_url}"></beans:property>
    <beans:property name="username" value="${jdbc_username}"></beans:property>
    <beans:property name="password" value="${jdbc_password}"></beans:property>
    <!-- 初始化连接大小 -->
    <beans:property name="initialSize" value="0"></beans:property>
    <!-- 连接池最大使用连接数量 -->
    <beans:property name="maxActive" value="20"></beans:property>
    <!-- 连接池最大空闲 -->
    <beans:property name="maxIdle" value="20"></beans:property>
    <!-- 连接池最小空闲 -->
    <beans:property name="minIdle" value="0"></beans:property>
    <!-- 获取连接最大等待时间 -->
    <beans:property name="maxWait" value="60000"></beans:property>
</beans:bean>

<beans:bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <beans:property name="dataSource" ref="dataSource"></beans:property>
</beans:bean>

<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.spy.single.service.impl.UserServiceImpl.*(..))"/>
</aop:config>

Mapper:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.spy.single.dao.UserMapper" >
    <insert id="insert" parameterType="cn.spy.single.model.User">
        INSERT INTO single_user (name, age, pwd, create_time, modify_time, deleted)
        VALUES(
            #{name},
            #{age},
            #{pwd},
            #{createTime},
            #{modifyTime},
            #{deleted}
        )
    </insert>
    
    <insert id="insertVip" parameterType="cn.spy.single.model.Vip">
        INSERT INTO single_vip (vip_name, vip_create_time)
        VALUES(
            #{name},
            #{createTime}
        )
    </insert>
</mapper>
@Service("userService")
public class UserServiceImpl extends BaseService implements UserService{
    
    @Resource
    private UserMapper userMapper;

    @Override
    public Result insertUser(User user, Vip vip) throws SysException {
        Result result = new Result();
        
        if (user == null) {
            throw new SysException("Hello SysException");
        }
        
        userMapper.insert(user);
        userMapper.insertVip(vip);
        return result;
    }
}

测试:添加一条name为空的记录和name不为空的记录

public class SpringTest {
    
    public static void main(String[] args) throws SysException {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
        UserService us = ac.getBean("userService", UserService.class);
        User lyf = new User(null, "刘亦菲", 20, "123456789", new Date(), new Date(), false);
        Vip vip = new Vip(null, null, new Date());
        us.insertUser(lyf, vip);
    }
}

结果:



注解方式

<?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:aop="http://www.springframework.org/schema/aop" 
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    
    <context:property-placeholder location="classpath:/config.properties" />
    
    <!-- 配置Druid数据库连接池 -->
    <beans:bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <beans:property name="driverClassName" value="${jdbc_driverClass}"></beans:property> 
        <beans:property name="url" value="${jdbc_url}"></beans:property>
        <beans:property name="username" value="${jdbc_username}"></beans:property>
        <beans:property name="password" value="${jdbc_password}"></beans:property>
        <!-- 初始化连接大小 -->
        <beans:property name="initialSize" value="0"></beans:property>
        <!-- 连接池最大使用连接数量 -->
        <beans:property name="maxActive" value="20"></beans:property>
        <!-- 连接池最大空闲 -->
        <beans:property name="maxIdle" value="20"></beans:property>
        <!-- 连接池最小空闲 -->
        <beans:property name="minIdle" value="0"></beans:property>
        <!-- 获取连接最大等待时间 -->
        <beans:property name="maxWait" value="60000"></beans:property>
    </beans:bean>
    
    <!-- 指定注解方式实现事务 -->
    <tx:annotation-driven transaction-manager="txManager"/>
    
    <!-- 配置事务管理器类 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>
@Service("userService")
public class UserServiceImpl extends BaseService implements UserService{
    
    @Resource
    private UserMapper userMapper;
    
    @Transactional
    @Override
    public Result insertUser(User user, Vip vip) throws SysException {
        Result result = new Result();
        
        if (user == null) {
            throw new SysException("Hello SysException");
        }
        
        userMapper.insert(user);
        userMapper.insertVip(vip);
        return result;
    }
}

测试结果:


相关文章

  • spring事务用法

    Spring事务传播范围 propagation="REQUIRED"如果方法运行时,已经处于一个事务之中,那么直...

  • 关于事务的思考

    Spring对于事务的支持 Spring事务接口 Spring事务管理器 Spring并不直接管理事务,而是提供多...

  • Spring事务

    Spring 事务 分类 Spring可以支持编程式事务和声明式事务。 编程式事务 实现 Spring使用事务管理...

  • Spring中实现事务方式

    Spring 中实现事务的方式 Spring 并不直接支持事务,只有当数据库支持事务时,Spring 才支持事务,...

  • Spring事务的传播特性引发的一场血案

    Spring事务的传播特性是对于Spring事务管理的一项特殊配置;Spring事务基于Spring AOP特性,...

  • Spring 事务实现分析

    1. Spring 事务简介 Spring 本身并不实现事务,Spring事务 的本质 还是 底层数据库 对事务的...

  • Spring注解--事务(一):基本用法

    1. 概念理解 事务是一系列的动作,它们综合在一起才是一个完整的工作单元,这些动作必须全部完成,如果其中一个失败,...

  • spring04

    Spring JdbcTemplate学习 Spring 声明式事务 xml配置实现 Spring 声明式事务 注...

  • 程序员之Spring

    1. Spring事务 spring的事务实现原理Spring事务将connection放入到当前线程的threa...

  • 面前温习

    Spring事务传播特性的浅析——事务方法嵌套调用的迷茫 解惑 spring 嵌套事务

网友评论

      本文标题:spring事务用法

      本文链接:https://www.haomeiwen.com/subject/aetyvqtx.html