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:com.qwazr.library.test.MybatisTest.java

License:Apache License

protected void checkSession(SqlSessionFactory sessionFactory) {
    Assert.assertNotNull(sessionFactory);
    final SqlSession session = sessionFactory.openSession();
    try {/*from  w ww.  j  av  a 2 s .co  m*/
        final Connection connection = session.getConnection();
    } catch (PersistenceException e) {
        // It is okay to not be able to establish a mysql connection for this test
        // Any other exception is an error
        if (e.getCause() instanceof MySQLNonTransientConnectionException)
            return;
        throw e;
    } finally {
        IOUtils.close(session);
    }
}

From source file:das.orm.ORMBackendConnector.java

License:Apache License

public SqlSession createDBSession(Connection conn, boolean keepThisConnection) {
    log.trace(">>> createDBSession");
    if (sqlSessionFactory != null) {
        SqlSession ses;
        if (conn != null) {
            if (keepThisConnection) {
                connection = conn;//from w  w w  .  j  av  a  2 s  .  c om
            }
            ses = sqlSessionFactory.openSession(conn);
        } else {
            if ((keepDBConnection || keepThisConnection) && (connection != null)) {
                ses = sqlSessionFactory.openSession(connection);
            } else {
                ses = sqlSessionFactory.openSession();
                connection = ses.getConnection();
            }
        }
        return ses;
    } else
        return null;
}

From source file:examples.animal.data.BindingTest.java

License:Apache License

@Test
public void testBindInSelectList() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {//  www.  ja va2  s  .  c  om
        Connection connection = sqlSession.getConnection();

        PreparedStatement ps = connection
                .prepareStatement("select brain_weight + ? as calc from AnimalData where id = ?");
        ps.setDouble(1, 1.0);
        ps.setInt(2, 1);

        ResultSet rs = ps.executeQuery();
        double calculatedWeight = 0.0;
        if (rs.next()) {
            calculatedWeight = rs.getDouble("CALC");
        }

        rs.close();
        ps.close();

        assertThat(calculatedWeight).isEqualTo(1.005);
    } catch (SQLException e) {
        fail("SQL Exception", e);
    } finally {
        sqlSession.close();
    }
}

From source file:examples.animal.data.BindingTest.java

License:Apache License

@Test
public void testBindInWeirdWhere() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {//w  ww .  j  ava2s  .co m
        Connection connection = sqlSession.getConnection();

        PreparedStatement ps = connection
                .prepareStatement("select brain_weight from AnimalData where brain_weight + ? > ? and id = ?");
        ps.setDouble(1, 1.0);
        ps.setDouble(2, 1.0);
        ps.setInt(3, 1);

        ResultSet rs = ps.executeQuery();
        double calculatedWeight = 0.0;
        if (rs.next()) {
            calculatedWeight = rs.getDouble("BRAIN_WEIGHT");
        }

        rs.close();
        ps.close();

        assertThat(calculatedWeight).isEqualTo(.005);
    } catch (SQLException e) {
        fail("SQL Exception", e);
    } finally {
        sqlSession.close();
    }
}

From source file:io.starter.datamodel.Sys.java

License:Open Source License

/**
 * this method checks things and sends back a 200 if all is OK otherwise an
 * error code is sent/*from  w w w. j a va2  s .  c o  m*/
 * 
 * used for system monitoring
 * 
 * @param query
 * @param servletRequest
 * @param servletResponse
 * @return
 * @throws IOException
 * @throws ServletException
 * @throws JSONException
 * @throws SQLException
 */
@GET
@Path("systemcheck")
@Produces(MediaType.APPLICATION_JSON)
public String getSystemCheck(@Context HttpServletRequest servletRequest,
        @Context HttpServletResponse servletResponse)
        throws IOException, ServletException, JSONException, SQLException {

    JSONObject ret = new JSONObject();
    try {
        SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION);
        Connection connection = session.getConnection();
        ret.put("MyBatis DB Connection Status", connection.isValid(10000));
        return ret.toString();
    } catch (Exception e) {
        servletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}

From source file:io.starter.datamodel.Sys.java

License:Open Source License

/**
 * this method returns a JSON string with a summarized set of data for the
 * entire starter system/*from  ww w .  ja va  2s . c  o  m*/
 * 
 * includes:
 * 
 * Top Content Leader board System-wide Alliances
 * 
 * @param query
 * @param servletRequest
 * @param servletResponse
 * @return
 * @throws IOException
 * @throws ServletException
 * @throws JSONException
 * @throws SQLException
 */
@GET
@Path("stats")
@Produces(MediaType.APPLICATION_JSON)
public String getStats(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse)
        throws IOException, ServletException, JSONException, SQLException {

    String jsonStr = "";
    Map namevals = new HashMap();

    // System-wide eazy squeezy

    User u = (User) servletRequest.getSession(true).getAttribute(SESSION_VAR_USER);

    SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION);
    Connection connection = session.getConnection();

    try {

        namevals.put("system.totalusers", this.getValueFromDB("SELECT COUNT(id) as ct FROM user", connection));

        namevals.put("system.totalcontent",
                this.getValueFromDB("SELECT COUNT(id) as ct FROM content", connection));

        namevals.put("system.totalalliances",
                this.getValueFromDB("SELECT COUNT(id) as ct FROM role WHERE id > 100", connection));

        namevals.put("system.totalshares", this.getValueFromDB(
                "SELECT COUNT(id) FROM acl WHERE target_type = 2 AND principle_id = 2 AND principle_type = 1 AND permission = 3",
                connection));

        namevals.put("system.totalsocialshares", this.getValueFromDB(
                "SELECT COUNT(syslog.id) as CT FROM syslog WHERE ( event_type = 25 OR event_type = 26) AND syslog.description LIKE '%OK [%' ORDER BY CT desc",
                connection));

        namevals.put("system.totalratings",
                this.getValueFromDB("SELECT COUNT(id) as CT FROM content_rating", connection));

        namevals.put("system.totalcategories",
                this.getValueFromDB("SELECT COUNT(id) as CT FROM category", connection));

        namevals.put("system.totallogins", this.getValueFromDB(
                "SELECT COUNT(syslog.id) as CT FROM syslog WHERE event_type = 0 AND syslog.description LIKE '%OK [%' ORDER BY CT desc",
                connection));

        // Top Content -- the easiest
        ContentData cdx = new ContentData();

        String lx = cdx.list("top", servletRequest, servletResponse);
        JSONArray jaray = new JSONArray(lx);

        for (int t = 0; t < jaray.length(); t++) {
            namevals.put("topcontent." + t, jaray.get(t));
        }

        // Leader board
        // Top Content -- the easiest
        if (servletRequest.getParameter("leaderboard") != null) {
            try {
                lx = UserData.list("leaders", servletRequest, servletResponse);
                jaray = new JSONArray(lx);
                int lx1 = jaray.length() - 1;
                for (int t = 0; t < jaray.length(); t++) {
                    namevals.put("leader." + t, jaray.get(lx1 - t));
                }
            } catch (Exception e) {
                ; // couldn't get leaderboard
            }
        }

        // Alliances
        try {
            lx = RoleData.list("top", servletRequest, servletResponse);
            jaray = new JSONArray(lx);
            for (int t = 0; t < jaray.length(); t++) {
                namevals.put("alliance." + t, jaray.get(t));
            }
        } catch (Exception e) {
            ; // couldn't get alliances
        }

        // JSONify
        jsonStr = new JSONObject(namevals).toString();
        // oh yes, record it for posterity... this is going to come in
        // handy...
        Syslog logEntry = new Syslog();

        logEntry.setDescription("OK [ ANONYMOUS -1 ], [GET] [stats " + jsonStr.substring(0, 100) + "]");

        logEntry.setEventType(SystemConstants.LOG_EVENT_TYPE_SYSTEM_CONTENT);
        logEntry.setSourceId(-1);
        logEntry.setSourceType(SystemConstants.TARGET_TYPE_SYSTEM);
        logEntry.setTimestamp(new java.util.Date(System.currentTimeMillis()));

        session.insert("io.starter.dao.SyslogMapper.insert", logEntry);
        session.commit();

    } catch (Exception x) {
        Logger.log("Getting System Stats Failed: " + x.toString());
    }

    return jsonStr;

}

From source file:me.kafeitu.activiti.extra.helper.RuntimeTaskHelper.java

License:Apache License

/**
 * /*from ww  w.ja  va 2  s.  c  o m*/
 * 
 * @param taskId
 *          ID?
 * @param userIds
 *          
 */
public void addSign(String taskId, String... userIds) {

    // open new session
    SqlSession sqlSession = openSession();
    PreparedStatement ps = null;

    try {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        String taskDefinitionKey = task.getTaskDefinitionKey();

        // ?ACT_RU_EXECUTION
        // ???
        ExecutionEntity executionEntityOfMany = (ExecutionEntity) runtimeService.createNativeExecutionQuery()
                .sql("select * from ACT_RU_EXECUTION where PARENT_ID_ = (select ID_ from ACT_RU_EXECUTION where PARENT_ID_ = '"
                        + processInstanceId + "') limit 1")
                .singleResult();
        String processDefinitionId = executionEntityOfMany.getProcessDefinitionId();

        // ?ID
        TablePage listPage = managementService.createTablePageQuery().tableName("ACT_GE_PROPERTY").listPage(2,
                2);
        Map<String, Object> idMap = listPage.getRows().get(0);

        // ?ID
        Long nextId = Long.parseLong(idMap.get("VALUE_").toString());

        Connection connection = sqlSession.getConnection();

        for (String userId : userIds) {

            // ???
            long count = taskService.createTaskQuery().taskDefinitionKey(taskDefinitionKey)
                    .processInstanceId(processInstanceId).taskAssignee(userId).count();
            if (count > 0) {
                logger.warn("??{}, {}", userId, taskDefinitionKey);
                continue;
            }

            // ???
            Long newExecutionId = ++nextId;

            int counter = 1;
            ps = connection.prepareStatement(
                    "insert into ACT_RU_EXECUTION values(?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            ps.setString(counter++, newExecutionId.toString()); // ID
            ps.setString(counter++, processInstanceId); // PROC_INST_ID_
            ps.setString(counter++, executionEntityOfMany.getBusinessKey()); // BUSINESS_KEY_
            ps.setString(counter++, executionEntityOfMany.getParentId()); // PARENT_ID_
            ps.setString(counter++, processDefinitionId); // PROC_DEF_ID_
            ps.setString(counter++, executionEntityOfMany.getSuperExecutionId()); // SUPER_EXEC_
            ps.setString(counter++, executionEntityOfMany.getActivityId()); // ACT_ID_
            ps.setString(counter++, "TRUE"); // IS_ACTIVE_
            ps.setString(counter++, "TRUE"); // IS_CONCURRENT_
            ps.setString(counter++, "FALSE"); // IS_SCOPE_
            ps.setString(counter++, "FALSE"); // IS_EVENT_SCOPE_
            ps.setInt(counter++, 1); // SUSPENSION_STATE_
            ps.setInt(counter++, executionEntityOfMany.getCachedEntityState()); // CACHED_ENT_STATE_
            ps.executeUpdate();

            // 
            // runtime task
            Long newTaskId = ++nextId;
            counter = 1;
            ps = connection.prepareStatement(
                    "insert into act_ru_task values(?, 1, ?, ?, ?, ?, null, null, ?, null, ?, null, ?, ?, null, '1')");
            ps.setString(counter++, newTaskId.toString());
            ps.setString(counter++, newExecutionId.toString());
            ps.setString(counter++, processInstanceId);
            ps.setString(counter++, processDefinitionId);
            ps.setString(counter++, task.getName());
            ps.setString(counter++, taskDefinitionKey);
            ps.setString(counter++, userId);
            ps.setInt(counter++, task.getPriority());
            ps.setTimestamp(counter++, new Timestamp(System.currentTimeMillis()));
            ps.executeUpdate();

            // history task
            counter = 1;
            ps = connection.prepareStatement(
                    "insert into act_hi_taskinst values(?, ?, ?, ?, ?, null, ?, null, null, ?, ?, null, null, null, ?, null)");
            ps.setString(counter++, newTaskId.toString());
            ps.setString(counter++, processDefinitionId + "'");
            ps.setString(counter++, taskDefinitionKey + "'");
            ps.setString(counter++, processInstanceId);
            ps.setString(counter++, newExecutionId.toString());
            ps.setString(counter++, task.getName());
            ps.setString(counter++, userId);
            ps.setTimestamp(counter++, new Timestamp(System.currentTimeMillis()));
            ps.setInt(counter++, task.getPriority());
            ps.executeUpdate();

            // ID
            String updateNextId = "update ACT_GE_PROPERTY set VALUE_ = ? where NAME_ = ?";
            ps = connection.prepareStatement(updateNextId);
            ps.setLong(1, nextId);
            ps.setString(2, "next.dbid");

            /*
             * ??
             */
            List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(processInstanceId).variableNameLike("nrOf%").list();
            Integer nrOfInstances = 0;
            Integer nrOfActiveInstances = 0;
            for (HistoricVariableInstance var : list) {
                if (var.getVariableName().equals("nrOfInstances")) {
                    nrOfInstances = (Integer) var.getValue();
                } else if (var.getVariableName().equals("nrOfActiveInstances")) {
                    nrOfActiveInstances = (Integer) var.getValue();
                }
            }

            // ??
            nrOfInstances++;
            nrOfActiveInstances++;

            String updateVariablesOfMultiinstance = "update ACT_HI_VARINST set LONG_ = ?, TEXT_ = ? where EXECUTION_ID_ = ? and NAME_ = ?";
            ps = connection.prepareStatement(updateVariablesOfMultiinstance);
            ps.setLong(1, nrOfInstances);
            ps.setString(2, String.valueOf(nrOfInstances));
            ps.setString(3, executionEntityOfMany.getParentId());
            ps.setString(4, "nrOfInstances");
            ps.executeUpdate();

            ps.setLong(1, nrOfInstances);
            ps.setString(2, String.valueOf(nrOfActiveInstances));
            ps.setString(3, executionEntityOfMany.getParentId());
            ps.setString(4, "nrOfActiveInstances");
            ps.executeUpdate();

        }

        sqlSession.commit();
    } catch (Exception e) {
        logger.error("failed to add sign for countersign", e);
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                // do nothing
            }
        }
        sqlSession.close();
    }

}

From source file:net.oletalk.dbexecutor.util.MyBatisUtil.java

public static boolean runStatementsInFiles(List<String> filenames) throws VersionException {
    SqlSession session = null;
    Connection conn = null;//  w  ww .j a  va 2 s  .  c om
    boolean success = false;
    try {
        // get the config
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        SqlSessionFactory manager = new SqlSessionFactoryBuilder().build(reader);
        reader.close();

        session = manager.openSession();
        conn = session.getConnection();
        // run the sql
        success = runFiles(filenames, conn);

    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
            try {
                conn.close();
            } catch (SQLException sqe) {
                sqe.printStackTrace();
            }
        }
    }
    return success;

}

From source file:optional.OptionalTest.java

License:Apache License

@BeforeClass
public static void setUp() throws Exception {
    // create an SqlSessionFactory
    Reader reader = Resources.getResourceAsReader("optional/mybatis-config.xml");
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    reader.close();/*from   www.j  a v  a 2  s .co  m*/

    // populate in-memory database
    SqlSession session = sqlSessionFactory.openSession();
    Connection conn = session.getConnection();
    reader = Resources.getResourceAsReader("optional/CreateDB.sql");
    ScriptRunner runner = new ScriptRunner(conn);
    runner.setLogWriter(null);
    runner.runScript(reader);
    reader.close();
    session.close();
}

From source file:org.activiti.engine.impl.persistence.db.DbSqlSessionFactory.java

License:Apache License

public static void executeSchemaResource(String operation, String databaseName,
        SqlSessionFactory sqlSessionFactory) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    boolean success = false;
    try {//from   w w  w  . j a  v a 2s. c om
        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.finest("\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");
}