mybatis连接数据库出错获取不到SQLsession

采用mybatis连接数据库时候出现的问题描述:

数据库连接配置正确,mybatis-config数据库等部分配置均正确,连接数据库是OK的

<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>

此时通过MybatisUtil测试可以获取到sqlsession,并打印出来;

然后配置jopo及对应的xml文件正确,此时发现将jopo对应的xml文件注册到mybatis-config时,添加如下信息后

<mappers>
<mapper resource="com/yusys/entity/StudentMapper.xml"/>
</mappers>

反而获取不到数据库连接,得不到sqlsession,打印出来为null;

最终对比检查发现问题出在jopo对应配置文件中,如下标黄部分

<mapper namespace="com.yusys.entity.StudentMapper">
<select id="selectById" parameterType="java.lang.Integer" resultType="Student">
select * from student where id=#{id}
</select>
</mapper>

该属性resultType应该对应完全限定名,否则找不到对应的类,不能形成映射,故而,在通过代码测试

InputStream is = MybatisUtil.class.getClassLoader()
.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
session = sf.openSession();

的时候,加载mybatis-config.xml到mappers的注册信息时候不能正确加载,故而导致上面is流错误,从而后续session也就不能获取。

更改如下,在mybatis-config.xml中添加别名与Student对应上,如下:

<typeAliases>
<typeAlias type="com.yusys.entity.Student" alias="Student"/>
<package name="com.yusys.entity"/>
</typeAliases>

此时问题解决。

另一种办法是将属性resultType更改为其完全限定名

同时需要注意的是:

mybatis-config.xml配置文件配置时,要注意节点顺序

顺序同错误提示信息一致:

元素类型为 "configuration" 的内容必须匹配 "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,plugins?,environments?

,databaseIdProvider?,mappers?)"

例如:将typeAliase写在properties前面打印session同样会是null

<configuration>
<typeAliases>
<typeAlias type="com.yusys.entity.Student" alias="Student"/>
<package name="com.yusys.entity"/>
</typeAliases>
<properties resource="db.properties"></properties>

有时eclipse还会提示错误,configuration下面会出现红色曲线进行提示

尤其要注意的是,在mybatis编写的pojo.xml和mybatis-config.xml的编写过程中一定要细心对应起来,不能多也不能少,否则均会报空,也就是session均会为null,比如别名里面配置一个Emp,但是实际src的POJO包下和pojo.xml中均没有体现,则就会报null,在这里一定要关联考虑,要删删干净,要加加全面,不得马虎。

比如

<typeAliases>
<typeAlias type="com.yusys.entity.Student" alias="Student"/>
<typeAlias type="com.yusys.entity.udent" alias="udent"/>    ============多余添加一个
<package name="com.yusys.entity"/>
</typeAliases>

 运行结果会是

开启的+++session:null

Exception in thread "main" java.lang.NullPointerException  ===========空指针异常,因为多余的POJO不存在,无法编译通过
at com.yusys.test.Test.getStuById(Test.java:16)
at com.yusys.test.Test.main(Test.java:31)

在注册表中也不能多,如下:

<mappers>
<mapper resource="com/yusys/dao/StudentMapper.xml"/>

<mapper/>                            这个地方多出的一个空的映射注册表也不行,同样运行时候获取不到session

</mappers>

本博主支持并坚持原创,本博客文章将以原创为主。
原文地址:https://www.cnblogs.com/xiaoyao-001/p/8092781.html