domain.User;
import com.winterchen.mapper.UserMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisDemo2ApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void test(){
userMapper.insert("winterchen", "123456", "12345678910");
User u = userMapper.findUserByPhone("12345678910");
Assert.assertEquals("winterchen", u.getName());
}
}
12345678910111213141516171819202122232425262728293031
测试结果
说明已经成功了。
如果出现mapper注入不了的情况,请检查版本,当前博客的搭建方法只适合1.5.*版本的,如果你的版本是2.0以上的版本,请参照我的另一篇博客的mybatis的配置:springboot2.0整合mybatis
事务管理(重要)
我们在开发企业应用时,对于业务人员的一个操作实际是对数据读写的多步操作的结合。由于数据操作在顺序执行的过程中,任何一步操作都有可能发生异常,异常会导致后续操作无法完成,此时由于业务逻辑并未正确的完成,之前成功操作数据的并不可靠,需要在这种情况下进行回退。
为了测试的成功,请把测试的内容进行替换,因为之前测试的时候已经将数据生成了,重复的数据会对测试的结果有影响
@Test
@Transactional
public void test(){
userMapper.insert("张三", "123456", "18600000000");
int a = 1/0;
userMapper.insert("李四", "123456", "13500000000");
User u = userMapper.findUserByPhone("12345678910");
Assert.assertEquals("winterchen", u.getName());
}12345678910
只需要在需要事务管理的方法上添加 @Transactional 注解即可,然后我们启动测试,会发现异常之后,数据库中没有产生数据。
如果大家想对springboot事务管理有更加详细的了解,欢迎大家查看: springboot事务管理详解
源码:https://github.com/WinterChenS/springboot-mybatis-demo2/
来源:CSDN
原文:https://blog.csdn.net/Winter_chen001/article/details/78622141
版权声明:本文为博主原创文章,转载请附上博文链接!