获取sqlsession时的空指针异常
DBAccess代码:
package icoc.jmteam.TestOfMybatis.dao; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class DBAccess { private static Reader reader; private static SqlSessionFactory sessionFactory; private static SqlSession session; public static SqlSession getSession() throws IOException{ //通过配置文件获取数据库链接相关信息(配置文件放在src下) reader=Resources.getResourceAsReader("Configuration.xml"); //通过配置信息构建SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader); //打开会话SqlSession session=sessionFactory.openSession(); return session; } private DBAccess(){} }
测试获取链接类
package icoc.jmteam.TestOfMybatis.dao; import java.io.IOException; import org.apache.ibatis.session.SqlSession; public class MybatisTest { SqlSession session; public void TestToConnect(){ try { session=DBAccess.getSession(); if(session!=null){ System.out.println("创建会话成功"); }else{ System.out.println("创建会话失败"); } } catch (IOException e) { System.out.println("异常,创建会话失败"); }finally{ session.close(); System.out.println("会话已关闭"); } } public static void main(String args[]){ new MybatisTest().TestToConnect(); } }
异常信息如下:
SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/Howard/MyEclipse/work_spaces/TestOfMybatis/WebRoot/WEB-INF/lib/slf4j-log4j12-1.7.12.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/D:/My%20Projects/%e5%b7%a5%e5%85%b7%e7%ae%b1/Mybatis%e6%a0%b8%e5%bf%83jar%e5%8c%85/mybatis-3.3.0/lib/slf4j-log4j12-1.7.12.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory] Exception in thread "main" java.lang.NullPointerException at icoc.jmteam.TestOfMybatis.dao.MybatisTest.TestToConnect(MybatisTest.java:21) at icoc.jmteam.TestOfMybatis.dao.MybatisTest.main(MybatisTest.java:30)