工具包之创建SqlSessionFactory

package com.keyrisk.untils;

import java.io.InputStream;

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 SqlSessionFactoryUntils {

   

  private final static Class<SqlSessionFactoryUntils> LOCK = SqlSessionFactoryUntils.class;

  private static SqlSessionFactory sqlSessionFactory = null;

  //重构构造方法 使其不能通过new来实例化
  private SqlSessionFactoryUntils(){}

  public static SqlSessionFactory getSqlSessionFactory() {
    //加锁是为在放置多线程中多次实例化this的对象,保证唯一性
    synchronized (LOCK) {
      if(sqlSessionFactory!=null){
        return sqlSessionFactory;
      }
      String resource = "mybatis-config.xml";
      InputStream inputStream;
      try {
        inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }
  return sqlSessionFactory;
  }

  public static SqlSession openSqlSession(){
    if(sqlSessionFactory==null){
      getSqlSessionFactory();
    }
    return sqlSessionFactory.openSession();
  }

}

posted on 2019-01-12 17:55  meta-one  阅读(163)  评论(0编辑  收藏  举报

导航