采用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>