All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.siwenyan.query.MyBatisUtils Maven / Gradle / Ivy

There is a newer version: 1.25
Show newest version
package com.github.siwenyan.query;

import com.github.siwenyan.common.EasyProperties;
import com.github.siwenyan.common.StringTools;
import com.github.siwenyan.common.Sys;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

public class MyBatisUtils {

    public static final Logger log = Logger.getLogger(MyBatisUtils.class.getName());

    public static boolean getSqlSessionFactory(EasyProperties config, FactoryContainer factoryContainer, String mybatisConfigFilePath, String driverKey, String urlKey, String usernameKey, String passwordKey, String usernameKey1, String passwordKey1) {
        log.debug("envset=" + config.getProperty(EasyProperties.ENVSET));

        String url = config.getProperty(urlKey);
        log.warn("url=" + url);
        if (null == factoryContainer.properties || !url.equals(factoryContainer.properties.getProperty("url"))) {
            factoryContainer.reset();
        }

        if (null != factoryContainer.sqlSessionFactory) {
            return true;
        } else {
            try {
                factoryContainer.properties.setProperty("driver", config.getProperty(driverKey));
                factoryContainer.properties.setProperty("url", url);
                factoryContainer.properties.setProperty("username", config.getPropertyDeep(usernameKey));
                factoryContainer.properties.setProperty("password", config.getPropertyDeep(passwordKey));
                log.debug("factoryContainer.properties=" + factoryContainer.properties);

                File file = Sys.findFile(mybatisConfigFilePath);
                Reader reader = new FileReader(file);
                XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder(reader, null, factoryContainer.properties);
                Configuration configuration = xmlConfigBuilder.parse();

                factoryContainer.sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
                if (isValid(factoryContainer.sqlSessionFactory)) {
                    return true;
                } else {
                    String username1 = config.getProperty(usernameKey1);
                    String password1 = config.getProperty(passwordKey1);
                    if (StringTools.isEmpty(username1) && !StringTools.isEmpty(password1)) {
                        return false;
                    } else {
                        factoryContainer.properties.setProperty("username", username1);
                        factoryContainer.properties.setProperty("password", password1);
                        reader = new FileReader(file);
                        xmlConfigBuilder = new XMLConfigBuilder(reader, null, factoryContainer.properties);
                        configuration = xmlConfigBuilder.parse();
                        factoryContainer.sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
                        if (isValid(factoryContainer.sqlSessionFactory)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private static boolean isValid(SqlSessionFactory sqlSessionFactory) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            //mysql
            session.getConnection().prepareStatement("select 1;").executeQuery();
        } catch (Exception e) {
            try (SqlSession session = sqlSessionFactory.openSession()) {
                //oracle
                session.getConnection().prepareStatement("select 1 from dual").executeQuery();
            } catch (Exception ex) {
                return false;
            }
        }
        return true;
    }

    public static SqlSessionFactory getSqlSessionFactory(String className) {
        try {
            ISqlSessionFactoryProvider provider = (ISqlSessionFactoryProvider) Class.forName(className).newInstance();
            SqlSessionFactory sqlSessionFactory = provider.getSqlSessionFactory();
            return sqlSessionFactory;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void execute(SqlSessionFactory sqlSessionFactory, Reader sqlReader, boolean autocommit, boolean stopOnError) {

        SqlSession session = null;
        try {
            session = sqlSessionFactory.openSession();
            ScriptRunner runner = new ScriptRunner(session.getConnection());
            if (autocommit) {
                runner.setAutoCommit(true);
                runner.setStopOnError(stopOnError);
            } else {
                runner.setAutoCommit(false);
            }
            runner.runScript(sqlReader);
            session.commit();
            runner.closeConnection();
        } catch (Exception e) {
            log.error("Fail to execute sql: " + e.getMessage());
            try {
                session.rollback();
            } catch (Exception e1) {
                log.error("Fail to rollback: " + e1.getMessage());
            }
            throw new RuntimeException(e);
        } finally {
            try {
                session.close();
            } catch (Exception e) {
                log.error("Fail to close session: " + e.getMessage());
            }
        }

    }

    public static List> query(SqlSession sqlSession, String sql) throws SQLException {
        ResultSet rs = sqlSession.getConnection().prepareStatement(sql).executeQuery();
        ResultSetMetaData md = rs.getMetaData();
        int columns = md.getColumnCount();
        List> list = new ArrayList<>();
        while (rs.next()) {
            Map row = new LinkedHashMap(columns);
            for (int i = 1; i <= columns; ++i) {
                row.put(md.getColumnName(i), rs.getObject(i));
            }
            list.add(row);
        }
        return list;
    }

    public static int firstIndexOf(List> rows, Object value, String column) {
        if (null == rows || rows.size() <= 0 || null == column) {
            return -1;
        }
        if (null == value) {
            for (int i = 0; i < rows.size(); i++) {
                if (!rows.get(i).containsKey(column) || null == rows.get(i).get(column)) {
                    return i;
                }
            }
        } else {
            for (int i = 0; i < rows.size(); i++) {
                if (value.equals(rows.get(i).get(column))) {
                    return i;
                }
            }
        }
        return -1;
    }

    public static class FactoryContainer {
        public SqlSessionFactory sqlSessionFactory;
        public Properties properties;

        public void reset() {
            sqlSessionFactory = null;
            properties = new Properties();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy