[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
映射器Mapper实现事务的原理:
mapper本质是一个接口代理类,调用接口等某个方法后,获取字符串等于接口全路径名称+方法名去缓存里面找相应的sql语句,然后调用Transaction#getConnection获取数据库连接,后续的提交回滚也是调用这个接口等方法。
sqlsession实现事务的原理:
同上,可以设置自动提交事务
mybatis集成spring实现事务的原理
1、spring实现事务有3种方法,声明式事务包括xml和注解,编程实现事务也就是利用spring事务相关API,xml和注解本质上aop+编程实现事务;
public class UserService { private final PlatformTransactionManager
transactionManager; public UserService(PlatformTransactionManager
transactionManager) { this.transactionManager = transactionManager; } public
void createUser() { 1 TransactionStatus txStatus = transactionManager.
getTransaction(new DefaultTransactionDefinition()); try { 2 userMapper.
insertUser(user); } catch (Exception e) { 3 transactionManager.rollback(txStatus
); throw e; } 4 transactionManager.commit(txStatus); } }
代码1设置自动提交为false,表示开启一个事务;代码2底层会调用Transaction接口的实现类SpringTransaction,把数据库连接放到ThreadLocal,如果后面再有mapper或者sqlsession调用Transaction#getConnection方法,就会获取保存在ThreadLocal里面的数据库连接;代码3和代码4则会获取上面等数据库连接进行提交和回滚。可以知道最开始去获取数据库连接的是代码1,后面代码都是直接从ThreadLocal缓存里面拿。
为什么DataSourceTransactionManager和mybatis需要同一个数据库源?
答:首先DataSourceTransactionManager会去数据库源获取数据库连接,然后放到ThreadLocal,mybatis去SpringTransaction拿数据库连接,得到的是上面ThreadLocal的数据库连接。
还有一个疑问,不在事务里面执行mapper方法是自动提交,在事务里面mapper则是手动提交,这是怎么实现的?