Suppose that I have an application using ibatis 2 and spring 1. I have an external class that calls the dao method. What will happen if the following code is run:
// external class
public void doSomething() {
try {
daoLayer.startTransaction();
daoLayer.firstOperation();
daoLayer.secondOperation();
} finally {
daoLayer.endTransaction();
}
}
// dao layer which extends from org.springframework.orm.ibatis.support.SqlMapClientDaoSupport.SqlMapClientDaoSupport
public void startTransaction() { sqlMap.startTransaction(); }
public void firstOperation() { sqlMap.update("someQuery"); }
public void secondOperation() { sqlMap.update("someOtherQuery"); }
public void endTransaction() { sqlMap.endTransaction(); }
Will this code cause database connections to be leaked?
No. but to commit data, you need to include sqlMap.commitTransaction()
after daoLayer.secondOperation()
.
Will end transaction be run on the same transaction/db connection which executed the startTransaction, firstOperation, and secondOperation methods? Or might dbcp/ibatis pick a different connection out of the pool?
Yes .. if are opening a transaction you need to close it otherwise database server doesn't close the transaction and it will be expired as per server settings.
What could I do to test and make sure that the same connection is used for all the operations and that the transaction is working correctly?
In java: check logs for connection id. You can also check database server for assigned connection id.
Would anything change if I moved all my logic into a single method in the dao? Would that be more transaction safe?
No matter, if you have a single or multiple DAO operations in a single transaction.