关于不用Spring将MyBatis的SqlSession事务交给Struts2管理的做法

原创!转载请注明地址 http://ycde2009.iteye.com/blog/1861026
在这里主要是用拦截器的思想来对Mybatis的session进行commit和close的操作。
还需要做的就是把打开的SqlSession加入到ThreadLocal里面,以后每次用到就去ThreadLocal里面找,能找到就返回,不能找到,就新建一个,并用ThreadLocal.set()保存到ThreadLocal。
在拦截器里面invocation.invoke();后关闭资源。
将session与当前线程绑定
public class SQLSessionThreadLocal {
    public static final ThreadLocal session = new ThreadLocal();
    public static SqlSession currentSession() {
        SqlSession s = (SqlSession)session.get();
        if(s == null){
            s = MyBatisUtil.getSqlSessionFactory().openSession();
// MyBatisUtil.getSqlSessionFactory()获得一个
            session.set(s);
        }
        return s;
    }
       public static void clearCurrentSession() {
        SqlSession s = (SqlSession)session.get();
        if(s != null){
            s.commit();
            s.close();
        }
        session.set(null);
        //当前线程清空session,如果不清空,则在调用的时候可能会抛出异常:
        //org.apache.ibatis.executor.ExecutorException: Executor was closed
    }
}

--------------------注意------------------
在使用struts2拦截器来管理mybatis的事物的时候,在拦截器的方法intercept()里,应该在invoke的前后,调用自己写的工具方法clearCurrentSession(),来清空当前线程里面存放的session。
拦截器里的方法:
public String intercept(ActionInvocation arg0) throws Exception {
        // 调用方法,在当前线程中,清空上一次的session
        SQLSessionThreadLocal.clearCurrentSession();
       
        String result = arg0.invoke();
        // 调用方法,清空本次的session
        SQLSessionThreadLocal.clearCurrentSession();
       
        return result;
}

你可能感兴趣的:(struts,mybatis)