001/**
002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.mybatisflex.core.mybatis;
017
018import com.mybatisflex.core.FlexConsts;
019import com.mybatisflex.core.FlexGlobalConfig;
020import com.mybatisflex.core.dialect.DbType;
021import com.mybatisflex.core.dialect.DbTypeUtil;
022import com.mybatisflex.core.exception.FlexExceptions;
023import org.apache.ibatis.builder.xml.XMLConfigBuilder;
024import org.apache.ibatis.exceptions.ExceptionFactory;
025import org.apache.ibatis.executor.ErrorContext;
026import org.apache.ibatis.session.Configuration;
027import org.apache.ibatis.session.SqlSessionFactory;
028import org.apache.ibatis.session.SqlSessionFactoryBuilder;
029
030import java.io.IOException;
031import java.io.InputStream;
032import java.io.Reader;
033import java.util.Properties;
034
035public class FlexSqlSessionFactoryBuilder extends SqlSessionFactoryBuilder {
036
037    @Override
038    public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
039        try {
040            // 需要 mybatis v3.5.13+
041            // https://github.com/mybatis/mybatis-3/commit/d7826d71a7005a8b4d4e0e7a020db0f6c7e253a4
042            XMLConfigBuilder parser = new XMLConfigBuilder(FlexConfiguration.class, reader, environment, properties);
043            return build(parser.parse());
044        } catch (Exception e) {
045            throw ExceptionFactory.wrapException("Error building SqlSession.", e);
046        } finally {
047            ErrorContext.instance().reset();
048            try {
049                if (reader != null) {
050                    reader.close();
051                }
052            } catch (IOException e) {
053                // Intentionally ignore. Prefer previous error.
054            }
055        }
056    }
057
058
059    @Override
060    public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
061        try {
062            // 需要 mybatis v3.5.13+
063            // https://github.com/mybatis/mybatis-3/commit/d7826d71a7005a8b4d4e0e7a020db0f6c7e253a4
064            XMLConfigBuilder parser = new XMLConfigBuilder(FlexConfiguration.class, inputStream, environment, properties);
065            return build(parser.parse());
066        } catch (Exception e) {
067            throw ExceptionFactory.wrapException("Error building SqlSession.", e);
068        } finally {
069            ErrorContext.instance().reset();
070            try {
071                if (inputStream != null) {
072                    inputStream.close();
073                }
074            } catch (IOException e) {
075                // Intentionally ignore. Prefer previous error.
076            }
077        }
078    }
079
080
081    @Override
082    public SqlSessionFactory build(Configuration configuration) {
083        if (!FlexConfiguration.class.isAssignableFrom(configuration.getClass())) {
084            throw FlexExceptions.wrap("only support FlexMybatisConfiguration.");
085        }
086
087        SqlSessionFactory sessionFactory = super.build(configuration);
088        DbType dbType = DbTypeUtil.getDbType(configuration.getEnvironment().getDataSource());
089
090        //设置全局配置的 sessionFactory 和 dbType
091        initGlobalConfig(configuration, sessionFactory, dbType);
092
093        printBanner();
094
095        return sessionFactory;
096    }
097
098
099    private void printBanner() {
100        if (!FlexGlobalConfig.getDefaultConfig().isPrintBanner()) {
101            return;
102        }
103        String banner = "  __  __       _           _   _       _____ _           \n" +
104                " |  \\/  |_   _| |__   __ _| |_(_)___  |  ___| | _____  __\n" +
105                " | |\\/| | | | | '_ \\ / _` | __| / __| | |_  | |/ _ \\ \\/ /\n" +
106                " | |  | | |_| | |_) | (_| | |_| \\__ \\ |  _| | |  __/>  < \n" +
107                " |_|  |_|\\__, |_.__/ \\__,_|\\__|_|___/ |_|   |_|\\___/_/\\_\\\n" +
108                "         |___/ v" + FlexConsts.VERSION + " https://mybatis-flex.com";
109        System.out.println(banner);
110    }
111
112    /**
113     * 设置全局配置
114     *
115     * @param config
116     * @param sessionFactory
117     */
118    private void initGlobalConfig(Configuration config, SqlSessionFactory sessionFactory, DbType dbType) {
119        FlexGlobalConfig flexGlobalConfig = new FlexGlobalConfig();
120        flexGlobalConfig.setSqlSessionFactory(sessionFactory);
121        flexGlobalConfig.setDbType(dbType);
122        flexGlobalConfig.setConfiguration(config);
123
124        String environmentId = config.getEnvironment().getId();
125        FlexGlobalConfig.setConfig(environmentId, flexGlobalConfig);
126    }
127
128
129}