网站开发语言在线检测,游戏网址,团队云智能网站建设,dede减肥网站源码文章目录 前言一、同一张表1.业务代码2.测试代码3.测试结果 二、不同表1.业务代码2.测试代码3.测试结果 总结 前言
本文将介绍在springboot中使用Transactional注解来完成对数据库事务的操作#xff0c;保证数据一致性。 一、同一张表
1.业务代码
Controller
Controller
p… 文章目录 前言一、同一张表1.业务代码2.测试代码3.测试结果 二、不同表1.业务代码2.测试代码3.测试结果 总结 前言
本文将介绍在springboot中使用Transactional注解来完成对数据库事务的操作保证数据一致性。 一、同一张表
1.业务代码
Controller
Controller
public class StudentInfoController {/*** 相同表之间的事务* param s1* param s2* return*/public int transactional(StudentInfo s1,StudentInfo s2) {return studentInfoService.transactional(s1,s2);}
}Service
Service
public class StudentInfoService {Autowiredprivate StudentInfoMapper studentInfoMapper;/*** 测试事务*/Transactionalpublic int transactional(StudentInfo s1,StudentInfo s2) {int count0;count studentInfoMapper.insertSelective(s1);
// if(count1){
// throw new RuntimeException(ex);
// }count studentInfoMapper.insertSelective(s2);return count;}
}2.测试代码
RunWith(SpringRunner.class)
SpringBootTest(classes SpringbootStart.class)
public class SpringbootStartTest {Autowiredprivate StudentInfoController studentInfoController;
Testpublic void test(){transactional();}public void transactional(){StudentInfo s1new StudentInfo();s1.setId(t1);s1.setName(zs);s1.setIdType(sfz);s1.setIdNumber(100);StudentInfo s2new StudentInfo();s2.setId(t2);s2.setName(ls);s2.setIdType(sfz);s2.setIdNumber(200);studentInfoController.transactional(s1,s2);System.out.println(success);}
}3.测试结果
正常情况下,程序处理完成,插入了两条数据没问题 接下来,打开service中注释,主动抛出异常
二、不同表
1.业务代码
Controller
Controller
public class StudentInfoController extends BaseController{/*** 不同表之间的事务* param s1* param s2* return*/public int diffTransactional(StudentInfo s1, StudentCurriculum s2) {return studentInfoService.diffTransactional(s1,s2);}
}Service
Service
public class StudentInfoService {Autowiredprivate StudentInfoMapper studentInfoMapper;Autowiredprivate StudentCurriculumMapper studentCurriculumMapper;/*** 测试事务*/Transactionalpublic int diffTransactional(StudentInfo s1, StudentCurriculum s2) {int count0;count studentInfoMapper.insertSelective(s1);
// if(count1){
// throw new RuntimeException(ex);
// }count studentCurriculumMapper.insertSelective(s2);return count;}
}2.测试代码
RunWith(SpringRunner.class)
SpringBootTest(classes SpringbootStart.class)
public class SpringbootStartTest {Autowiredprivate StudentInfoController studentInfoController;
Testpublic void test(){diffTransactional();}public void diffTransactional(){StudentInfo s1new StudentInfo();s1.setId(t3);s1.setName(zs);s1.setIdType(sfz);s1.setIdNumber(100);StudentCurriculum s2new StudentCurriculum();s2.setId(4);s2.setCurriculumName(1);s2.setTeacher(zjg);studentInfoController.diffTransactional(s1,s2);System.out.println(success);}
}3.测试结果
正常情况下,程序处理完成,插入了两条数据没问题 接下来,打开service中注释,主动抛出异常 总结
回到顶部