事务: 说白了就是在一个connection里面做了一堆的事情, 在特定的时间点 [完成,异常] 进行提交或回滚.
所以, 无论是否Spring的TransactionManager还是自己的Servlet上的事务控制, 都是基于在一个事务单元内的一个connection上的, 所以, 你要将connection绑定在一个ThreadLocal上, 让里面所有的jdbc操作使用这个connection就好, 在Servlet的所有jdbc操作完成后, 再进行显示的commit 或 rollback.
下面的代码随手写的, 只是用于说明问题.
[code="java"]
SessionConnectionUtil {
static ThreadLocal holder = new ThreadLocal();
public static getConnection() {
if (holder.get() == null) {
holder.sut(new Connection());
}
return (Connection) holder.get();
}
public static closeConnection() {
holder.set(null);
}
}
CustomServlet extends HttpServlet {
CustomDao dao;
service() {
try {
dao.doSomething();
SessionConnectionUtil.getConnection().commit();
} catch (Exception e) {
SessionConnectionUtil.getConnection().rollback();
} finally {
SessionConnectionUtil.closeConnection();
}
}
}
CustomDao {
doSomething() {
Connection connection = SessionConnectionUtil.getConnection();
...
}
}[/code]