spring 只读事务 设置异常回滚事务 |
您所在的位置:网站首页 › 形容变装的句子 › 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: 事务回滚,数据未更新
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |