今天开始接触MyBatis,在测试类建立数据库连接时一直遇到空指针sqlSession报错,写下这篇解决方案供参考:
错误提示
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error opening session. Cause: java.lang.NullPointerException
### Cause: java.lang.NullPointerException
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(DefaultSqlSessionFactory.java:100)
at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession(DefaultSqlSessionFactory.java:47)
at com.zhongruan.test.Test01.main(Test01.java:18)
Caused by: java.lang.NullPointerException
at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(DefaultSqlSessionFactory.java:95)
... 2 more
Process finished with exit code 1
经过调试发现,问题出在config.xml里面;在mybatis配置时,可能由于我们开发时的数据库环境和最终上线时的数据库环境不同,因此可以在配置文件中配置多个数据库环境;在< envirments> 标签里有一个default属性,该属性对应的是下面的不同的< enviroment > 的id属性;default的值为哪一个id,则代表此时使用的是哪一个environment数据库环境。
由于我直接复制老师给的代码,在default一栏的value值是" "即空值,因此获取enviornment时会出现空指针报错,把default值补充为下面出现的"development"即可
<environments default="development">//就是这里
<environment id="development">
<!-- 配置JDBC事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源 数据源采用数据库连接池技术 c3p0 druid-->
<dataSource type="POOLED">
<!-- 数据库相关配置 -->
<!-- mysql 8 以上驱动 -->
<!--<property name="driver" value="com.mysql.cj.jdbc.Driver"/>-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test_db?serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
最后问题解决,数据库成功存储