Example usage for org.apache.ibatis.session SqlSession getConnection

List of usage examples for org.apache.ibatis.session SqlSession getConnection

Introduction

In this page you can find the example usage for org.apache.ibatis.session SqlSession getConnection.

Prototype

Connection getConnection();

Source Link

Document

Retrieves inner database connection.

Usage

From source file:org.activiti.engine.test.db.MetaDataTest.java

License:Apache License

public void testMetaData() {
    ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getCommandExecutor()
            .execute(new Command<Object>() {
                public Object execute(CommandContext commandContext) {
                    // PRINT THE TABLE NAMES TO CHECK IF WE CAN USE METADATA INSTEAD
                    // THIS IS INTENDED FOR TEST THAT SHOULD RUN ON OUR QA INFRASTRUCTURE TO SEE IF METADATA 
                    // CAN BE USED INSTEAD OF PERFORMING A QUERY THAT MIGHT FAIL
                    try {
                        SqlSession sqlSession = commandContext.getSession(DbSqlSession.class).getSqlSession();
                        ResultSet tables = sqlSession.getConnection().getMetaData().getTables(null, null, null,
                                null);/*from w  w  w. j  a v  a  2 s  . c  o m*/
                        while (tables.next()) {
                            ResultSetMetaData resultSetMetaData = tables.getMetaData();
                            int columnCount = resultSetMetaData.getColumnCount();
                            for (int i = 1; i <= columnCount; i++) {
                                log.info("result set column {}|{}|{}|{}", i, resultSetMetaData.getColumnName(i),
                                        resultSetMetaData.getColumnLabel(i), tables.getString(i));
                            }
                            log.info("-------------------------------------------------------");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            });
}

From source file:org.activiti.impl.db.Db.java

License:Apache License

public static void executeSchemaResource(String operation, SqlSessionFactory sqlSessionFactory) {
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); // Not quite sure if this is the right setting? We do want multiple updates to be batched for performance ...
    boolean success = false;
    try {//from w w  w. jav a2 s  .  c o  m
        Connection connection = sqlSession.getConnection();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String resource = "org/activiti/db/" + operation + "/activiti.h2." + operation + ".sql";
        InputStream inputStream = classLoader.getResourceAsStream(resource);
        if (inputStream == null) {
            throw new ActivitiException("resource '" + resource + "' is not available for creating the schema");
        }

        Exception exception = null;
        byte[] bytes = IoUtil.readInputStream(inputStream, resource);
        String ddlStatements = new String(bytes);
        StringTokenizer tokenizer = new StringTokenizer(ddlStatements, ";");
        while (tokenizer.hasMoreTokens()) {
            String ddlStatement = tokenizer.nextToken().trim();
            if (!ddlStatement.startsWith("#")) {
                Statement jdbcStatement = connection.createStatement();
                try {
                    log.fine("\n" + ddlStatement);
                    jdbcStatement.execute(ddlStatement);
                    jdbcStatement.close();
                } catch (Exception e) {
                    if (exception == null) {
                        exception = e;
                    }
                    log.log(Level.SEVERE, "problem during schema " + operation + ", statement '" + ddlStatement,
                            e);
                }
            }
        }

        if (exception != null) {
            throw exception;
        }

        success = true;

    } catch (Exception e) {
        throw new ActivitiException("couldn't create db schema", e);

    } finally {
        if (success) {
            sqlSession.commit(true);
        } else {
            sqlSession.rollback(true);
        }
        sqlSession.close();
    }

    log.fine("activiti db schema creation successful");
}

From source file:org.activiti.impl.persistence.IbatisPersistenceSessionFactory.java

License:Apache License

public void executeSchemaResource(String operation, SqlSessionFactory sqlSessionFactory) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    boolean success = false;
    try {//from  ww  w . ja va2  s .c o m
        Connection connection = sqlSession.getConnection();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String resource = "org/activiti/db/" + operation + "/activiti." + databaseName + "." + operation
                + ".sql";
        InputStream inputStream = classLoader.getResourceAsStream(resource);
        if (inputStream == null) {
            throw new ActivitiException("resource '" + resource + "' is not available for creating the schema");
        }

        Exception exception = null;
        byte[] bytes = IoUtil.readInputStream(inputStream, resource);
        String ddlStatements = new String(bytes);
        StringTokenizer tokenizer = new StringTokenizer(ddlStatements, ";");
        while (tokenizer.hasMoreTokens()) {
            String ddlStatement = tokenizer.nextToken().trim();
            if (!ddlStatement.startsWith("#")) {
                Statement jdbcStatement = connection.createStatement();
                try {
                    log.fine("\n" + ddlStatement);
                    jdbcStatement.execute(ddlStatement);
                    jdbcStatement.close();
                } catch (Exception e) {
                    if (exception == null) {
                        exception = e;
                    }
                    log.log(Level.SEVERE, "problem during schema " + operation + ", statement '" + ddlStatement,
                            e);
                }
            }
        }

        if (exception != null) {
            throw exception;
        }

        success = true;

    } catch (Exception e) {
        throw new ActivitiException("couldn't create db schema", e);

    } finally {
        if (success) {
            sqlSession.commit(true);
        } else {
            sqlSession.rollback(true);
        }
        sqlSession.close();
    }

    log.fine("activiti db schema " + operation + " successful");
}

From source file:org.activiti5.engine.test.db.MetaDataTest.java

License:Apache License

public void testMetaData() {
    ProcessEngineConfigurationImpl activiti5ProcessEngineConfig = (ProcessEngineConfigurationImpl) processEngineConfiguration
            .getActiviti5CompatibilityHandler().getRawProcessConfiguration();
    activiti5ProcessEngineConfig.getCommandExecutor().execute(new Command<Object>() {
        public Object execute(CommandContext commandContext) {
            // PRINT THE TABLE NAMES TO CHECK IF WE CAN USE METADATA INSTEAD
            // THIS IS INTENDED FOR TEST THAT SHOULD RUN ON OUR QA INFRASTRUCTURE TO SEE IF METADATA 
            // CAN BE USED INSTEAD OF PERFORMING A QUERY THAT MIGHT FAIL
            try {
                SqlSession sqlSession = commandContext.getSession(DbSqlSession.class).getSqlSession();
                ResultSet tables = sqlSession.getConnection().getMetaData().getTables(null, null, null, null);
                while (tables.next()) {
                    ResultSetMetaData resultSetMetaData = tables.getMetaData();
                    int columnCount = resultSetMetaData.getColumnCount();
                    for (int i = 1; i <= columnCount; i++) {
                        log.info("result set column {}|{}|{}|{}", i, resultSetMetaData.getColumnName(i),
                                resultSetMetaData.getColumnLabel(i), tables.getString(i));
                    }/*from  w  ww  .  jav  a  2s .co m*/
                    log.info("-------------------------------------------------------");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });
}

From source file:org.apache.guacamole.auth.mysql.MySQLEnvironment.java

License:Apache License

@Override
public boolean isRecursiveQuerySupported(SqlSession session) {

    // Retrieve database version string from JDBC connection
    String versionString;//from  w  w w  . ja  v a 2  s . co  m
    try {
        Connection connection = session.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        versionString = metaData.getDatabaseProductVersion();
    } catch (SQLException e) {
        throw new PersistenceException(
                "Cannot determine whether " + "MySQL / MariaDB supports recursive queries.", e);
    }

    try {

        // Parse MySQL / MariaDB version from version string
        MySQLVersion version = new MySQLVersion(versionString);
        logger.debug("Database recognized as {}.", version);

        // Recursive queries are supported for MariaDB 10.2.2+ and
        // MySQL 8.0.1+
        return version.isAtLeast(MARIADB_SUPPORTS_CTE) || version.isAtLeast(MYSQL_SUPPORTS_CTE);

    } catch (IllegalArgumentException e) {
        logger.debug("Unrecognized MySQL / MariaDB version string: "
                + "\"{}\". Assuming database engine does not support " + "recursive queries.", session);
        return false;
    }

}

From source file:org.apache.mybatis.basetest.BaseTest.java

License:Apache License

@BeforeClass
public static void setUp() throws Exception {
    // create a SqlSessionFactory
    Reader reader = Resources.getResourceAsReader("org/apache/mybatis/basetest/mybatis-config.xml");
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    reader.close();// ww w  .j av a  2 s. c o  m

    // populate in-memory database
    SqlSession session = sqlSessionFactory.openSession();

    Connection conn = session.getConnection();
    reader = Resources.getResourceAsReader("org/apache/mybatis/basetest/CreateDB.sql");
    ScriptRunner runner = new ScriptRunner(conn);
    runner.setLogWriter(null);
    runner.runScript(reader);
    reader.close();

    session.close();
}

From source file:org.b3mn.poem.data.defaults.DataDefaults.java

License:Open Source License

public static void all() {
    try {/*from  www.  j  a v  a 2s.  c  o m*/
        //-- Check if already initialized
        Identity rootowner = Identity.instance("ownership");
        if (rootowner == null) {
            //-- Reset DB
            Reader reader = Resources.getResourceAsReader("org/b3mn/poem/tests/myibitis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();

            SqlSession session = sqlSessionFactory.openSession();
            Connection conn = session.getConnection();
            reader = Resources.getResourceAsReader("org/b3mn/poem/defaults/test_reset_mysql_db_schema.sql");
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.runScript(reader);
            reader.close();

            reader = Resources.getResourceAsReader("org/b3mn/poem/defaults/test_data.sql");
            runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.runScript(reader);
            reader.close();

            session.close();

            //-- Add test model/template
            String title = "Job #1";
            String type = "http://b3mn.org/stencilset/reporting#";
            String summary = "";
            User user = new User("public");

            URL testfile = DataDefaults.class.getResource("/data/newmodelhandler/test1_svg.xml");
            File file = new File(testfile.toURI());
            String svg = FileUtils.readFileToString(file, "UTF-8");

            testfile = DataDefaults.class.getResource("/data/newmodelhandler/test1_content_json.txt");
            file = new File(testfile.toURI());
            String data = FileUtils.readFileToString(file, "UTF-8");

            Identity.newModel(user.getIdentity(), title, type, summary, svg, data);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    /*      createIdentities();
          createInterations();
          createSettings();
          createStructures();*/
}

From source file:org.camunda.bpm.engine.test.db.MetaDataTest.java

License:Apache License

public void testMetaData() {
    ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getCommandExecutorTxRequired()
            .execute(new Command<Object>() {
                public Object execute(CommandContext commandContext) {
                    // PRINT THE TABLE NAMES TO CHECK IF WE CAN USE METADATA INSTEAD
                    // THIS IS INTENDED FOR TEST THAT SHOULD RUN ON OUR QA INFRASTRUCTURE TO SEE IF METADATA 
                    // CAN BE USED INSTEAD OF PERFORMING A QUERY THAT MIGHT FAIL
                    try {
                        SqlSession sqlSession = commandContext.getSession(DbSqlSession.class).getSqlSession();
                        ResultSet tables = sqlSession.getConnection().getMetaData().getTables(null, null, null,
                                null);//from www .j ava2 s.c o m
                        while (tables.next()) {
                            ResultSetMetaData resultSetMetaData = tables.getMetaData();
                            int columnCount = resultSetMetaData.getColumnCount();
                            for (int i = 1; i <= columnCount; i++) {
                                log.info("result set column " + i + " | " + resultSetMetaData.getColumnName(i)
                                        + " | " + resultSetMetaData.getColumnLabel(i) + " | "
                                        + tables.getString(i));
                            }
                            log.info("-------------------------------------------------------");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            });
}

From source file:org.camunda.bpm.engine.test.standalone.db.MetaDataTest.java

License:Apache License

public void testMetaData() {
    ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getCommandExecutorTxRequired()
            .execute(new Command<Object>() {
                public Object execute(CommandContext commandContext) {
                    // PRINT THE TABLE NAMES TO CHECK IF WE CAN USE METADATA INSTEAD
                    // THIS IS INTENDED FOR TEST THAT SHOULD RUN ON OUR QA INFRASTRUCTURE TO SEE IF METADATA
                    // CAN BE USED INSTEAD OF PERFORMING A QUERY THAT MIGHT FAIL
                    try {
                        SqlSession sqlSession = commandContext.getSession(DbSqlSession.class).getSqlSession();
                        ResultSet tables = sqlSession.getConnection().getMetaData().getTables(null, null, null,
                                null);/*from   ww w . ja  v a 2 s .c om*/
                        while (tables.next()) {
                            ResultSetMetaData resultSetMetaData = tables.getMetaData();
                            int columnCount = resultSetMetaData.getColumnCount();
                            for (int i = 1; i <= columnCount; i++) {
                                LOG.info("result set column " + i + " | " + resultSetMetaData.getColumnName(i)
                                        + " | " + resultSetMetaData.getColumnLabel(i) + " | "
                                        + tables.getString(i));
                            }
                            LOG.info("-------------------------------------------------------");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            });
}

From source file:org.camunda.bpm.qa.upgrade.scenarios.job.JobMigrationScenario.java

License:Apache License

@DescribesScenario("createJob")
public static ScenarioSetup triggerEntryCriterion() {
    return new ScenarioSetup() {
        public void execute(ProcessEngine engine, final String scenarioName) {

            final ProcessEngineConfigurationImpl engineConfiguration = (ProcessEngineConfigurationImpl) engine
                    .getProcessEngineConfiguration();
            CommandExecutor commandExecutor = engineConfiguration.getCommandExecutorTxRequired();

            // create a job with the scenario name as id and a null suspension state
            commandExecutor.execute(new Command<Void>() {
                public Void execute(CommandContext commandContext) {
                    Connection connection = null;
                    Statement statement = null;
                    ResultSet rs = null;

                    try {
                        SqlSession sqlSession = commandContext.getDbSqlSession().getSqlSession();
                        connection = sqlSession.getConnection();
                        statement = connection.createStatement();
                        statement.executeUpdate(
                                "INSERT INTO ACT_RU_JOB(ID_, REV_, RETRIES_, TYPE_, EXCLUSIVE_, HANDLER_TYPE_) "
                                        + "VALUES (" + "'" + scenarioName + "'," + "1," + "3," + "'timer',"
                                        + DbSqlSessionFactory.databaseSpecificTrueConstant
                                                .get(engineConfiguration.getDatabaseType())
                                        + "," + "'" + TimerStartEventJobHandler.TYPE + "'" + ")");
                        connection.commit();
                        statement.close();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    } finally {
                        try {
                            if (statement != null) {
                                statement.close();
                            }// w w w  .  j a  va 2  s .  co m
                            if (rs != null) {
                                rs.close();
                            }
                            if (connection != null) {
                                connection.close();
                            }
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return null;
                }
            });

        }
    };
}