【弄nèng - 化繁为简】Transactional同一

@Transactional,在一个事务中更新数据,在查询能查询到新数据

同一个类中

在一个事务中更新之后再查询能查询到最新的数据,毋庸置疑。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
java复制代码    @Autowired
private TestMapper testMapper;

@Transactional
public void testTransactional() {
System.out.println("1.====:" + testMapper.selectById(1).toString());
updateTestById("司马缸5");
System.out.println("2.====:" + testMapper.selectById(1).toString());
}

public void updateTestById(String name) {
TestEntity entity = new TestEntity();
entity.setId(1);
entity.setName(name);
testMapper.updateById(entity);
}

执行testTransactional()

输出

在这里插入图片描述

不同的类中

A更新,B查询,也能查询到新数据,因为B加入到A的事务中了。此时如果B中出现异常,AB中的操作都会回滚

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
java复制代码@Service
public class TestServiceImpl extends ServiceImpl<TestMapper, TestEntity> implements ITestService {

private static Map<String, String> map = Maps.newHashMap();
@Autowired
private TestMapper testMapper;

@Autowired
private TestServiceImpl2 testServiceImpl2;

@Transactional
public void testTransactional() {
System.out.println("1.====:" + testMapper.selectById(2));

updateTestById("司马缸2");

System.out.println("2.====:" + testMapper.selectById(2));

System.out.println("3.====:" + testServiceImpl2.get());
}

public void updateTestById(String name) {
TestEntity entity = new TestEntity();
entity.setId(1);
entity.setName(name);
testMapper.updateById(entity);
}
}



@Service
public class TestServiceImpl2 extends ServiceImpl<TestMapper, TestEntity> implements ITestService {

@Autowired
private TestMapper testMapper;

// @Transactional(propagation = Propagation.REQUIRES_NEW)
public TestEntity get() {
TestEntity entity = testMapper.selectById(2);
return entity;
}
}

执行testTransactional()

输出

image.png

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%