Spring boot Mybatis 整合(注解版)

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
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值