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?
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.