文章目录
- 前言
- 一、同一张表
- 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 {
@Autowired
private StudentInfoMapper studentInfoMapper;
/**
* 测试事务
*/
@Transactional
public int transactional(StudentInfo s1,StudentInfo s2) {
int count=0;
count += studentInfoMapper.insertSelective(s1);
// if(count==1){
// throw new RuntimeException("ex");
// }
count += studentInfoMapper.insertSelective(s2);
return count;
}
}
2.测试代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootStart.class)
public class SpringbootStartTest {
@Autowired
private StudentInfoController studentInfoController;
@Test
public void test(){
transactional();
}
public void transactional(){
StudentInfo s1=new StudentInfo();
s1.setId("t1");
s1.setName("zs");
s1.setIdType("sfz");
s1.setIdNumber("100");
StudentInfo s2=new 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 {
@Autowired
private StudentInfoMapper studentInfoMapper;
@Autowired
private StudentCurriculumMapper studentCurriculumMapper;
/**
* 测试事务
*/
@Transactional
public int diffTransactional(StudentInfo s1, StudentCurriculum s2) {
int count=0;
count += studentInfoMapper.insertSelective(s1);
// if(count==1){
// throw new RuntimeException("ex");
// }
count += studentCurriculumMapper.insertSelective(s2);
return count;
}
}
2.测试代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootStart.class)
public class SpringbootStartTest {
@Autowired
private StudentInfoController studentInfoController;
@Test
public void test(){
diffTransactional();
}
public void diffTransactional(){
StudentInfo s1=new StudentInfo();
s1.setId("t3");
s1.setName("zs");
s1.setIdType("sfz");
s1.setIdNumber("100");
StudentCurriculum s2=new StudentCurriculum();
s2.setId(4);
s2.setCurriculumName("1");
s2.setTeacher("zjg");
studentInfoController.diffTransactional(s1,s2);
System.out.println("success");
}
}
3.测试结果
正常情况下,程序处理完成,插入了两条数据没问题
接下来,打开service中注释,主动抛出异常
总结
回到顶部