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;
    }
}


你可能感兴趣的:(Mybatis实习笔记--2)