如何解决iBatis的嵌套事务问题?
假设我的项目中有以下结构(我使用 iBatis 作为 DAO):
public class UsersManager {
public void do {
mySqlMapClient.startTransaction();
// my code here
mySqlMapClient.endTransaction();
mySqlMapClient.commitTransaction();
}
}
public class StatsManager {
public void do {
mySqlMapClient.startTransaction();
// my code here
mySqlMapClient.endTransaction();
mySqlMapClient.commitTransaction();
}
}
public class App {
public void do {
myUsersManager.do();
myStatsManager.do(); // here I get an exception, because the transaction is already started
}
}
那么,我的问题是,如何解决这个问题?我的项目中有大约 150 多个交易,因此重写所有业务逻辑并不是一个简单的解决方案。对于这种情况有标准方法吗?我应该在哪里寻找?
Let's suppose I have the following structure in my project (I'm using iBatis as DAO):
public class UsersManager {
public void do {
mySqlMapClient.startTransaction();
// my code here
mySqlMapClient.endTransaction();
mySqlMapClient.commitTransaction();
}
}
public class StatsManager {
public void do {
mySqlMapClient.startTransaction();
// my code here
mySqlMapClient.endTransaction();
mySqlMapClient.commitTransaction();
}
}
public class App {
public void do {
myUsersManager.do();
myStatsManager.do(); // here I get an exception, because the transaction is already started
}
}
So, my question is, how can I solve this problem? I have like 150+ transactions in my project, so it's not easy solution to rewrite all biz logic. Is there ay standard approach for situations like this and where should I be looking at?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正是出于这个原因,您不应该在 DAO 内部拥有事务逻辑。
通常有一个服务层拥有数据库连接和工作单元。它启动事务,调用所有参与的 DAO,并在事务完成后进行清理。
Spring框架使用方面来实现事务逻辑。您将拥有所有这些 DAO 的接口。 Spring 将生成一个代理来以声明方式处理事务。也许您可以使用其中一些设计概念,即使您不使用 Spring。
或者直接学习Spring。它很好地支持 iBatis。
You should not have transaction logic inside DAOs for exactly this reason.
Usually there's a service layer that owns the database connection and the unit of work. It starts the transaction, calls all the participating DAOs, and cleans up after the transaction is complete.
The Spring framework uses aspects to implement transactional logic. You'd have interfaces for all those DAOs. Spring would generate a proxy that would handle the transaction declaratively. Maybe you could use some of those design concepts, even if you don't use Spring.
Or just learn Spring. It supports iBatis nicely.