1. 程式人生 > >mybatis下opening session時空指標異常

mybatis下opening session時空指標異常

先看錯誤資訊

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:23)
	at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(DefaultSqlSessionFactory.java:88)
	at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession(DefaultSqlSessionFactory.java:43)
	at com.swj.util.DbUtil.openSession(DbUtil.java:30)
	at com.swj.test.Test.main(Test.java:13)
Caused by: java.lang.NullPointerException
	at org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSessionFromDataSource(DefaultSqlSessionFactory.java:83)
	... 3 more
先找到錯誤的資訊是在factory.openSession()這裡,以為是factory沒有拿到,輸出了下factory發現是有物件存在的,

就很奇怪。- -應該是哪裡配置錯了 看下配置檔案 和獲取SqlSession的地方

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
	<properties resource="jdbc.properties"></properties>
	<typeAliases>
		<typeAlias type="com.swj.model.Person" alias="Person"/>
	</typeAliases>
	<environments default="database">
		<environment id="database">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED0">
				<property name="driver" value="${driver_}"/>
				<property name="url" value="${url_}"/>
				<property name="username" value="${username_}"/>
				<property name="password" value="${password_}"/>
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/swj/dao/PersonMapper.xml"/>
	</mappers>
</configuration>

package com.swj.util;

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;

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 DbUtil {
	private static SqlSessionFactory factory;
	
	private DbUtil(){}
	
	static{
		try {
			Resources.setCharset(Charset.forName("utf-8"));
			Reader reader = Resources.getResourceAsReader("mybatis.xml");
			factory = new SqlSessionFactoryBuilder().build(reader,"oracle");
		} catch (IOException e) {
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static SqlSession openSession(){
		return factory.openSession();
	}
	
	public static void close(SqlSession session){
		if(session!=null){
			session.close();
		}
	}
}

找了半天- -發現是在配置檔案裡的環境名字是database,而獲取factory時傳入的環境是oracle,開始以為是用的什麼資料庫傳的就是資料庫的名稱- -