spring 只读事务 设置异常回滚事务

@Transactional(readOnly = true)

将当前事务设置为只读事务,在该事务执行过程中只允许select语句执行,delete insert update均不可执行。

该特性的作用是:启动spring的优化策略。提高select语句执行效率。

@Transactional(rollbackFor = RuntimeException.class)

表示只有发生RuntimeException异常或该异常的子类异常才回滚

@Transactional(noRollbackFor = NullPointerException.class)

表示发生NullPointerException或该异常的子类异常不回滚,其他异常则回滚

package com.service;

import com.dao.AccountDao;
import com.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-09 07:09
 **/
@Service
public class Service02 {

    @Resource(name="accountDao")
    public AccountDao accountDao;

    @Transactional(noRollbackFor = NullPointerException.class)
    public void update(Account act) {

        accountDao.update(act);
        throw new NullPointerException();
    }
}

 ​​​@Transactional(noRollbackFor = NullPointerException.class)

发生NullPointerException异常时不回滚

test

package com;

import com.pojo.Account;
import com.service.Service01;
import com.service.Service02;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-09 07:47
 **/
public class IsolationTest {

    

    @Test
    public void testIsolation2(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        Service02 i2 = applicationContext.getBean("service02", Service02.class);
        Account act = new Account("004", 1000.0);
        i2.update(act);
    }
}

 before testing

after testing

 

数据更新,未回滚, 

 

 

不使用         ​@Transactional(noRollbackFor = NullPointerException.class)

package com.service;

import com.dao.AccountDao;
import com.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-09 07:09
 **/
@Service
public class Service02 {

    @Resource(name="accountDao")
    public AccountDao accountDao;

    @Transactional
    public void update(Account act) {

        accountDao.update(act);
        throw new NullPointerException();
    }
}

Before testing: 

After testing:

事务回滚,数据未更新 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值