@Transactional,在一个事务中更新数据,在查询能查询到新数据
同一个类中
在一个事务中更新之后再查询能查询到最新的数据,毋庸置疑。
代码
@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中的操作都会回滚
代码
@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()
输出