2019-01-15 · Develop

MyBatis 获取 JDBC Connection

项目使用 Mybatis 框架,但是有个别需求需要使用到 JDBC 的 Connection 所以记录下获取方式:

方式一: SqlSessionUtils

@Autowired
private SqlSessionTemplate template;

public void run(String sql) {
    Connection connection = null;
    Statement statement = null;
    ResultSet rt = null;
    try {
        sqlSession = SqlSessionUtils.getSqlSession(template.getSqlSessionFactory(), template.getExecutorType(), template.getPersistenceExceptionTranslator());
        connection = sqlSession.getConnection();
        statement = connection.createStatement();
        statement.execute(sql);
        rt = statement.getResultSet();
        // TODO
    } catch (Exception e) {
        // TODO 
    } finally {
        // try {
        //     if (rt != null) {
        //         rt.close();
        //     }
        //     if (statement != null) {
        //         statement.close();
        //     }
        //     if (connection != null) {
        //         connection.close();
        //     }
        // } catch (SQLException e) {
        //     // this never happens
        // }
        SqlSessionUtils.closeSqlSession(sqlSession, template.getSqlSessionFactory());
    }
}

方式二: Configuration

@Autowired
private SqlSessionTemplate template;

public void run(String sql) {
    Connection connection = null;
    Statement statement = null;
    ResultSet rt = null;
    List<Map<String, Object>> list = new ArrayList<>();
    try {
        connection = template.getConfiguration().getEnvironment().getDataSource().getConnection();
        statement = connection.createStatement();
        statement.execute(sql);
        rt = statement.getResultSet();
        // TODO
    } catch (Exception e) {
        // TODO
    } finally {
        try {
            // if (rt != null) {
            //     rt.close();
            // }
            // if (statement != null) {
            //     statement.close();
            // }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            // this never happens
        }
    }
}

无论是使用那种方式,最终都要关闭连接