@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
数据更新,未回滚,
文章来源地址https://www.toymoban.com/news/detail-489031.html
不使用 @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:
事务回滚,数据未更新
文章来源:https://www.toymoban.com/news/detail-489031.html
到了这里,关于spring 只读事务 设置异常回滚事务的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!