准备工作:
测试表:


pojo:
@Data
public class testA {
private int id;
private int a;
}
@Data
public class testB {
private int id;
private int b;
}
dao:
@Mapper
@Repository
public interface TestAMapper {
Integer addNumA();
}
@Mapper
@Repository
public interface TestBMapper {
Integer descNumB();
}
xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jarvis.msgserver.dao.TestAMapper">
<update id="addNumA">
update test_a set a=a+1 where id=1;
</update>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jarvis.msgserver.dao.TestBMapper">
<update id="descNumB">
update test_b set b=b-1 where id=1;
</update>
</mapper>
声明式事务
在主配置类加开启事务支持的注解:
@SpringBootApplication
@EnableTransactionManagement //开启事务支持
public class MsgserverApplication {
public static void main(String[] args) {
SpringApplication.run(MsgserverApplication.class, args);
}
}
在作为事务的service上加上@Transactional:
@Service
public class TestNumService {
@Autowired
private TestAMapper testAMapper;
@Autowired
private TestBMapper testBMapper;
//该方法作为一个事务运行
@Transactional
public void testNum(){
testAMapper.addNumA(); //test_a表的a字段+1
//int a = 1/0;
testBMapper.descNumB(); //test_b表的b字段-1
}
}
测试
int a=1/0 注释掉:


int a=1/0去掉注释,让其报错回滚:
a和b都还是10
@Transactional属性:
| 属性 | 说明 |
|---|---|
| propagation | 事务的传播行为,默认值为 REQUIRED。 |
| isolation | 事务的隔离度,默认值采用 DEFAULT |
| timeout | 事务的超时时间,默认值为-1,不超时。如果设置了超时时间(单位秒),那么如果超过该时间限制了但事务还没有完成,则自动回滚事务。 |
| readOnly | 只读事务。如果一次执行多条查询语句,例如统计查询,报表查询,在这种场景下,多条查询SQL必须保证整体的读一致性,否则,在前条SQL查询之后,后条SQL查询之前,数据被其他用户改变,则该次整体的统计查询将会出现读数据不一致的状态,此时,应该启用事务支持。在将事务设置成只读后,相当于将数据库设置成只读数据库,此时若要进行写的操作,会出现错误 |
| rollbackFor | 用于指定能够触发事务回滚的异常类型,如果有多个异常类型需要指定,各类型之间可以通过逗号分隔。{xxx1.class, xxx2.class,……} |
| noRollbackFor | 抛出 no-rollback-for 指定的异常类型,不回滚事务。{xxx1.class, xxx2.class,……} |
本文介绍了如何在SpringBoot中实现声明式事务管理。通过在主配置类添加@EnableTransactionManagement注解开启事务支持,并在Service层使用@Transactional进行事务声明。在测试过程中,展示了在发生错误时事务的回滚机制。
476

被折叠的 条评论
为什么被折叠?



