MyBatis-Plus:建立動態資料來源

zhilonng發表於2020-10-22

MyBatis-Plus:建立動態資料來源

簡述

由於一些業務場景需要,我們可能需要使用MyBatis-Plus動態連線資料庫,進行資料互動。

工具類

import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
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.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcSessionFactory {

    private static JdbcSessionFactory instance = null;

    private SqlSessionFactory sqlSessionFactory;

    private DataSourceConfig dataSourceConfig;

    private JdbcSessionFactory() {
    }

    /**
     * 嘗試獲取例項
     * @return
     */
    public static JdbcSessionFactory tryGetInstance() {
        if (instance == null) {
            throw new RuntimeException();
        }
        return instance;
    }

    /**
     * 獲取連線例項
     * @param jdbcUrl
     * @param name
     * @param password
     * @return
     */
    public static JdbcSessionFactory getInstance(String jdbcUrl, String name, String password) {
        if (instance == null) {
            instance = new JdbcSessionFactory();
            instance.createJdbcSessionFactory(jdbcUrl, "com.mysql.jdbc.Driver", name, password);
        }
        return instance;
    }

    /**
     * 測試資料庫連線
     * @param jdbcUrl
     * @param name
     * @param password
     * @return
     */
    public static Boolean sqlTest(String jdbcUrl, String name, String password) {
        return sqlTest(jdbcUrl, "com.mysql.jdbc.Driver", name, password);
    }

    /**
     * 獲取一個SqlSession會話
     * @return
     */
    public SqlSession getSqlSession() {
        return this.sqlSessionFactory.openSession();
    }

    public DataSourceConfig getDataSourceConfig() {
        return this.dataSourceConfig;
    }

    /**
     * 建立jdbcSession工廠
     * @param jdbcUrl
     * @param driver
     * @param name
     * @param password
     * @return
     */
    private Boolean createJdbcSessionFactory(String jdbcUrl, String driver, String name, String password) {
        if (!sqlTest(jdbcUrl, "com.mysql.jdbc.Driver", name, password)) {
            throw new RuntimeException("db connect time out");
        }
        // 儲存資料庫配置
        dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName(driver);
        dataSourceConfig.setUrl(jdbcUrl);
        dataSourceConfig.setUsername(name);
        dataSourceConfig.setPassword(password);

        DataSource dataSource =new PooledDataSource(driver,jdbcUrl,name,password);
        TransactionFactory transactionFactory =  new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.setDefaultStatementTimeout(8);

        // 分頁
        PageInterceptor pageInterceptor = new PageInterceptor();
        pageInterceptor.plugin(getPageHelper());
        configuration.addInterceptor(pageInterceptor);

        configuration.addMappers("com.cj.tools.mybatisplus.mapper");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        this.sqlSessionFactory = sqlSessionFactory;
        return true;
    }

    /**
     * 分頁外掛
     * @return
     */
    private PageHelper getPageHelper(){
        PageHelper pageHelper=new PageHelper();
        Properties properties=new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("reasonable", "true");
        pageHelper.setProperties(properties);
        return pageHelper;
    }

    /**
     * 測試資料庫連線
     * @param jdbcUrl
     * @param driver
     * @param name
     * @param password
     * @return
     */
    private static Boolean sqlTest(String jdbcUrl, String driver, String name, String password) {
        DataSource dataSource =new PooledDataSource(driver,jdbcUrl,name,password);
        try {
            dataSource.setLoginTimeout(5);
            dataSource.getConnection().getClientInfo();
        } catch (SQLException e) {
            return false;
        }
        return true;
    }
}

注意事項

1)如果進行多次連線,每次連線時注意進行sqlTest,否則可能出現連線不上問題。
2)分頁外掛如果不需要,可自行刪除

相關文章