解决问题记录-Cause: org.apache.ibatis.executor.ExecutorException: Executor was closed

解决问题:Cause: org.apache.ibatis.executor.ExecutorException: Executor was closed

问题意思:执行者被关闭了

在原有的项目上进行改造,使用Mybatis注解进行开发。在原有的代码上进行修改。

private  static StudentDao studentDao = null;
    static {
         InputStream resourceAsStream = null;
         SqlSessionFactory build = null;
         SqlSession sqlSession = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("MyBatisConfig.xml");
            build = new SqlSessionFactoryBuilder().build(resourceAsStream);
            sqlSession = build.openSession();
            studentDao = sqlSession.getMapper(StudentDao.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

看了挺久发现,使用的是静态代码块,那么这些代码只会在类加载时执行唯一一次,在调用studentDao方法之后就进行了关闭sqlSession,那么后续再一次调用,sqlSession已经被关闭了,而且不会创建新的sqlSession,只会在类加载时创建唯一一次,所以才会报Executor was closed 错误。

解决

private  static StudentDao studentDao = null;
private static SqlSession sqlSession= null;
private static SqlSessionFactory build = null;
static {
    try {
        InputStream resourceAsStream = Resources.getResourceAsStream("MyBatisConfig.xml");
        build = new SqlSessionFactoryBuilder().build(resourceAsStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public List<Student> findAll() {
    sqlSession = build.openSession();
    studentDao = sqlSession.getMapper(StudentDao.class);
    ArrayList<Student> all = studentDao.findAll();
    sqlSession.close();
    return all;
}

在每个方法中获取SqlSession对象,使用完成之后归还到连接池中。在静态代码块中,工厂对象只会创建一次,你可以在方法中创建SqlSession对象,根据不同的接口动态获取不同的代理对象,更加灵活,也不会出现Executor was closed 错误。

只作为个人记录,如有帮助不胜荣幸。

你可能感兴趣的:(问题记录)