博客

SpringBoot 事物管理

2020-07-01 10701 0

简介 不使用事物 定义好的cat类和dao 在junit测试中代码 cat 的构造器 public Cat(Integer id, Integer catAge, String catName) { this.id = id; this.catAge ...

不使用事物

定义好的cat类和dao 在junit测试中代码 cat 的构造器

public Cat(Integer id, Integer catAge, String catName) {
    this.id = id;
 this.catAge = catAge;
 this.catName = catName;
}

public Cat(Integer catAge, String catName) {
    this.catAge = catAge;
 this.catName = catName;
}

test 代码

@Test
public void transactionTest() throws Exception{
  Cat cat1 = new Cat(1,"cat1");
  Cat cat2 = new Cat(1,"cat2");
  Cat cat3 = new Cat(1,"cat3");
  Cat cat4 = new Cat(1,"cat12345678");
  Cat cat5 = new Cat(1,"cat5");
  catService.addCat(cat1);
  catService.addCat(cat2);
  catService.addCat(cat3);
  catService.addCat(cat4);
  catService.addCat(cat5);
}

注意 catname 数据库长度是10 则cat4 会报错 mark

而cat1 cat2 cat3 都插入成功 mark 而若这是一个希望保证完整性操作的情况 下,只需开启事物注解

使用事物

1搭建好springboot集成好数据库交互层 2开启事物很简单 在启动类上加上注解@EnableTransactionManagement mark

3然后在访问数据库的Service方法上添加注解 @Transactional 便可 @Transactional 注解

@Transactional
@Override
public void addCat(Cat cat) throws Exception {
    catMapper.insert(cat);
}

测试同样报错 只是数据库并没有cat123了 mark

点赞 0

标签云

文章评论

欢迎您:

博客

不求与人相比,但求超越自己,要哭就哭出激动的泪水,要笑就笑出成长的性格。

168 文章 2364985 浏览 3 评论

标签云

站点信息

  • 建站时间:2020-10-01
  • 更新时间:2026-11-09
  • 文章统计:168篇文章
  • 标签总数:166个
  • 加我微信:扫码,加我微信

目录