Mybatis实习笔记--2

package com.vitoh.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.Reader;

/**
 * Created by vitohuang on 15/10/22.
 */
public class MyBatisSessionFactory {

    private static String CONFIG = "mybatis.cfg.xml";

    private static final ThreadLocal<SqlSession> threadLoacl = new ThreadLocal<SqlSession>();

    private static SqlSessionFactory sessionFactory;

    private static Reader reader;

    static{
        buildSessionFactory();
    }

    /**
     * 初始化SqlSessionFactory
     */
    public static void buildSessionFactory(){
        try{
            //第一步读取配置文件信息
            reader = Resources.getResourceAsReader(CONFIG);
            //第二步通过 SqlSessionFactoryBuilder 实例化 SqlSessionFactory
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            System.out.println("SessionFactory 创建失败");
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库操作对象
     * @return
     */
    public static SqlSession getSession(){
        SqlSession session = (SqlSession)threadLoacl.get();
        if(session == null ){
            if(sessionFactory == null) buildSessionFactory();
            session = sessionFactory != null ? sessionFactory.openSession() : null;
            threadLoacl.set(session);
        }
        return session;
    }

    /**
     * 关闭数据库操作对象
     */
    public static void closeSession(){
        SqlSession session = (SqlSession)threadLoacl.get();
        if(session != null) session.close();
        threadLoacl.remove();
    }

    /**
     * 提交
     */
    public static void commit(){
        SqlSession session = (SqlSession)threadLoacl.get();
        if(session != null) session.commit();
    }

    /**
     * 回滚
     */
    public static void rollback(){
        SqlSession session = (SqlSession)threadLoacl.get();
        if(session != null) session.rollback();
    }

    /**
     * 获取SqlSessionFactory
     * @return
     */
    public static SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

af5a5f23220d1fe9dfc926c72fc61f32b6a.jpg

转载于:https://my.oschina.net/vitoh/blog/522047

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值