因为mongodb支持了事务,所以在程序中也使用了事务。但是要注意springboot的版本。如果找不到MongoTransactionManager这个类就是版本低了,需要用到mongodb中的事务的话,就要提升版本了。(温馨提醒:注意其他地方的改动如,Sort)
下面开始用代码来说明。
1、配置代码
首先的是mongodb的事务管理器配置。
@Configuration
public class MongoConfig {
@Bean
MongoTransactionManager transactionManager(MongoDbFactory factory){
return new MongoTransactionManager(factory);
}
}
2、使用到的entity,dao,repository
@Data
@Document(collection = "student")
public class Student {
private String id;
private String name;
private String code;
}
@Component
public class StudentDao {
@Autowired
StudentRepository studentRepository;
@Transactional
public boolean addStudent(Student student){
Student result = studentRepository.save(student);
//这个是错误
//int i = 1/0;
return result != null;
}
}
public interface StudentRepository extends MongoRepository<Student, String> {
}
3、测试用例代码
@SpringBootTest
class TestApplicationTests {
@Autowired
StudentDao studentDao;
@Test
void contextLoads() {
Student student = new Student();
student.setCode("190000");
student.setName("于禁");
studentDao.addStudent(student);
}
}
先运行正确的,查看集合中的数据,显示正常。
1.jpg
再讲注释的地方打开,如下:
@Component
public class StudentDao {
@Autowired
StudentRepository studentRepository;
@Transactional
public boolean addStudent(Student student){
Student result = studentRepository.save(student);
//这个是错误
int i = 1/0;
return result != null;
}
}
在修改下测试用例中的数据
@SpringBootTest
class TestApplicationTests {
@Autowired
StudentDao studentDao;
@Test
void contextLoads() {
Student student = new Student();
student.setCode("190001");
student.setName("于禁");
studentDao.addStudent(student);
}
}
运行测试用例,会报异常:
java.lang.ArithmeticException: / by zero
再去检测下集合中的数据;
2.jpg
毫无变化,则说明事务回滚。
4、结尾
愿善待美好。