zoukankan      html  css  js  c++  java
  • spring事务失效原因总结

    1.调用的方法不是 public 的:

      spring官方文档说明如下:When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

    2.自身调用问题:

    示例:方法methodB调用方法methodA,方法methodA添加了事务,事务也不会生效。

    @Transactional
    public void methodA() throws Exception {
    throw new RuntimeException();
    }

    /**
    * 这里调用methodA() 的事务将会失效
    */
    // @Transactional
    // @Transactional(rollbackFor = Exception.class)
    public void methodB() throws Exception {
    this.methodA();
    }

    3.捕捉异常没有抛出,事务不生效。


    @Transactional
    public void methodA() throws Exception {
    int id = 1;
    try {
    Test t = new Test();
    t.setId(id);
    t.setName("3");
    m.updateById(t);
    throw new Exception();
    } catch (Exception e) {
    e.printStackTrace();
    // throw new Exception();
    // throw new RuntimeException();

    } finally {
    Test test = m.selectById(id);
    log.info("test={}", m.selectById(id));
    }

    }

    4.捕捉异常后, 抛出非RuntimeException异常,事务不生效,需要配置 @Transactional(rollbackFor = Exception.class)即可生效
    @Transactional
    public void methodA() throws Exception {
    int id = 1;
    try {
    Test t = new Test();
    t.setId(id);
    t.setName("3");
    m.updateById(t);
    throw new Exception();
    } catch (Exception e) {
    e.printStackTrace();
    throw new Exception();
    // throw new RuntimeException();

    } finally {
    Test test = m.selectById(id);
    log.info("test={}", m.selectById(id));
    }
    // throw new RuntimeException();

    }


  • 相关阅读:
    并发编程 19—— 显式的Conditon 对象
    JVM实用参数——新生代垃圾回收
    设计模式 8 —— 适配器和外观模式
    并发编程 18—— 使用内置条件队列实现简单的有界缓存
    并发编程 17—— Lock
    Spring 事务管理 01 ——
    并发编程 16—— 线程池 之 原理二
    并发编程 15—— 线程池 之 原理一
    并发编程 14—— 线程池 之 整体架构
    java.util.logging.Logger 使用详解
  • 原文地址:https://www.cnblogs.com/liu-xiaolong/p/14081473.html
Copyright © 2011-2022 走看看