工具类获取SqlSesionFactory与SqlSession


/**
 * 通过单例模式,创建一个sqlSessionFactory
 * @author zomas
 */
public class MyBatisSqlSessionFactory {
    private static final String LOCATION="mybatis-config.xml";//MyBatis框架的总体配置文件
    //懒汉式单例模式(SqlSessionFactory一个应用里面只有一个所以最好这里使用单例模式)
    private static SqlSessionFactory sqlSessionFactory=null;
    private MyBatisSqlSessionFactory(){}
    //初始化SqlSessionFactory对象
    private static void init(){
        //加载配置文件(将配置文件加载到内存变为输入流)
        InputStream inputStream = null;
        try {//利用MyBatis封装的工具类的getResourceAsStream方法本质还是利用类加载器进行加载文件
            //获得了一个输入流(包含数据库的连接数据)
            inputStream = Resources.getResourceAsStream(LOCATION);
        } catch (IOException e) {
            System.out.println("Mybatis加载配置文件时失败");
            e.printStackTrace();
        }
        //通过SqlSessionFactoryBuilder对象来创建SqlSessionFactory工厂(这里使用创建者模式)
        //SqlSessionFactoryBuilder是SqlSessionFactory生成器
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //builder对象在创建SqlSessionFactory对象时,需要连接数据库的配置信息
        //(所有的配置信息都在mybatis-config.xml中这个文件已经被转换成了输入流所以直接)
        //利用build方法创建了sqlSessionFactory
        sqlSessionFactory=builder.build(inputStream);
    }
    //线程同步(防止出现线程不安全问题)
    //因为是单例模式
    //获取sqlSessionFactory对象
    /*
        也就是说每个线程都来获取SessionFactory对象
        为了防止一个线程运行一半被半路上拦下不让走所以加上synchronized让其一个线程走完在让下一个走
        下面的方法获取工厂类
        if判断是为了如果为null就创建,如果不是null就直接返回对象
     */
    public static synchronized SqlSessionFactory getSqlSessionFactory(){
        //进行判断是不是空是空就创建一个不是就直接返回,为了防止sqlSessionFactory直接返回的是个null
        if (sqlSessionFactory==null){
            //初始化SqlSessionFactory对象
            init();
        }
        return sqlSessionFactory;
    }
    //获取sqlSession对象
    public static SqlSession getSqlSession(){
        //不能直接用sqlSessionFactory变量调用
        //因为如果是null就会报空指针所以用get方法调用
        return getSqlSessionFactory().openSession();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值