1. 程式人生 > >mybatis之 SqlSessionFactory單例建立

mybatis之 SqlSessionFactory單例建立

新建MybatisSqlSessionFactory單例類,並例項化,使其有個SqlSessionFactory單例物件:

package com.mybatis3.util; 
import java.io.*; 
import org.apache.ibatis.io.Resources; 
import org.apache.ibatis.session.*; 
public class MyBatisSqlSessionFactory{ 
   private static  SqlSessionFactory sqlSessionFactory; 
   public static SqlSessionFactory getSqlSessionFactory(){ 
        if(sqlSessionFactory == null){ 
            InputStream inputStream; 
            try{ 
                inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
            }catch (IOException e){ 
                throw newRuntimeException(e.getCause()); 
      	  } 
        } 
        return sqlSessionFactory; 
    } 
   public static SqlSession openSession(){ 
       return getSqlSessionFactory().openSession(); 
    } 
}