/*
 * @Author: Kane
 * @Date: 2023-07-27 17:22:55
 * @LastEditors: Kane
 * @FilePath: /desktop_archievement_backend/src/main/java/com/cpic/xim/mybatis/utils/MybatisUtils.java
 * @Description: mybatis的工具集合
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */
package com.cpic.xim.mybatis.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
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 MybatisUtils
{
    private static HashMap<String, SqlSession> SessionMap = new HashMap<>();
    private static String DEFAULT_CONFIGFILE = "mybatis/mybatis-config.xml";

    /**
     * 
     * @param configFile
     * @return
     * @throws IOException
     */
    public static SqlSession getSqlSession( String configFile ) throws IOException
    {
        // 根据配置文件的路径，查找是否已经创建了对应的session
        SqlSession session = SessionMap.get( configFile );

        // 找到就直接返回
        if ( session != null )
        {
            return session;
        }

        // 没找到就创建一个
        InputStream configIS = Resources.getResourceAsStream( configFile );
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build( configIS );
        session = factory.openSession();

        // 保存
        SessionMap.put( configFile, session );

        return session;
    }

    public static SqlSession getSqlSession() throws IOException
    {
        // 根据配置文件的路径，查找是否已经创建了对应的session
        SqlSession session = SessionMap.get( DEFAULT_CONFIGFILE );

        // 找到就直接返回
        if ( session != null )
        {
            return session;
        }

        // 没找到就创建一个
        InputStream configIS = Resources.getResourceAsStream( DEFAULT_CONFIGFILE );
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build( configIS );
        session = factory.openSession();

        // 保存
        SessionMap.put( DEFAULT_CONFIGFILE, session );

        return session;
    }
}
