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.mirth.connect.server.controllers.DefaultDatabaseTaskController.java

License:Open Source License

@Override
public Map<String, DatabaseTask> getDatabaseTasks() throws Exception {
    Map<String, DatabaseTask> tasks = new HashMap<String, DatabaseTask>();
    SqlSession session = SqlConfig.getSqlSessionManager().openSession();

    try {//from  ww  w  . j  a va2s  .  c o  m
        Connection connection = session.getConnection();

        // Only add the task to remove OLD_CHANNEL if OLD_MESSAGE has already been dropped
        if (DatabaseUtil.tableExists(connection, "OLD_MESSAGE")) {
            DatabaseTask task = populateTask(new DatabaseTask(TASK_REMOVE_OLD_MESSAGE));
            logger.debug("Adding database task: " + task.getName());
            tasks.put(task.getId(), task);
        } else if (DatabaseUtil.tableExists(connection, "OLD_CHANNEL")) {
            DatabaseTask task = populateTask(new DatabaseTask(TASK_REMOVE_OLD_CHANNEL));
            logger.debug("Adding database task: " + task.getName());
            tasks.put(task.getId(), task);
        }

        if (DatabaseUtil.tableExists(connection, "OLD_ATTACHMENT")) {
            DatabaseTask task = populateTask(new DatabaseTask(TASK_REMOVE_OLD_ATTACHMENT));
            logger.debug("Adding database task: " + task.getName());
            tasks.put(task.getId(), task);
        }

        if (DatabaseUtil.tableExists(connection, "OLD_CODE_TEMPLATE")) {
            DatabaseTask task = populateTask(new DatabaseTask(TASK_REMOVE_OLD_CODE_TEMPLATE));
            logger.debug("Adding database task: " + task.getName());
            tasks.put(task.getId(), task);
        }

        DonkeyDao dao = Donkey.getInstance().getDaoFactory().getDao();
        try {
            Map<String, Long> localChannelIdMap = dao.getLocalChannelIds();
            Map<String, String> affectedChannels = new HashMap<String, String>();

            for (String channelId : localChannelIdMap.keySet()) {
                long localChannelId = localChannelIdMap.get(channelId);
                String tableName = "D_MM" + localChannelId;

                if (!DatabaseUtil.indexExists(connection, tableName, tableName + "_INDEX3")) {
                    affectedChannels.put(channelId, getChannelName(channelId));
                }
            }

            if (MapUtils.isNotEmpty(affectedChannels)) {
                DatabaseTask task = populateTask(new DatabaseTask(TASK_ADD_D_MM_INDEX3));
                task.setAffectedChannels(affectedChannels);
                logger.debug("Adding migration task: " + task.getName());
                tasks.put(task.getId(), task);
            }
        } finally {
            if (dao != null) {
                dao.close();
            }
        }
    } finally {
        session.close();
    }

    DatabaseTask currentTask = getCurrentTask();
    if (currentTask != null) {
        tasks.put(currentTask.getId(), currentTask);
    }

    return tasks;
}

From source file:com.mirth.connect.server.controllers.DefaultDatabaseTaskController.java

License:Open Source License

@Override
public String runDatabaseTask(String taskId) throws Exception {
    DatabaseTask databaseTask = getCurrentTask();

    if (databaseTask == null && taskRunLock.tryLock()) {
        try {//from  w  w  w . j a v a  2  s .com
            startTask(populateTask(new DatabaseTask(taskId)));

            if (taskId.equals(TASK_REMOVE_OLD_CHANNEL)) {
                executeUpdate("DROP TABLE OLD_CHANNEL");
                return "Table OLD_CHANNEL successfully dropped.";
            } else if (taskId.equals(TASK_REMOVE_OLD_MESSAGE)) {
                executeUpdate("DROP TABLE OLD_MESSAGE");
                return "Table OLD_MESSAGE successfully dropped.";
            } else if (taskId.equals(TASK_REMOVE_OLD_ATTACHMENT)) {
                executeUpdate("DROP TABLE OLD_ATTACHMENT");
                return "Table OLD_ATTACHMENT successfully dropped.";
            } else if (taskId.equals(TASK_REMOVE_OLD_CODE_TEMPLATE)) {
                executeUpdate("DROP TABLE OLD_CODE_TEMPLATE");
                return "Table OLD_CODE_TEMPLATE successfully dropped.";
            } else if (taskId.equals(TASK_ADD_D_MM_INDEX3)) {
                DonkeyDaoFactory daoFactory = Donkey.getInstance().getDaoFactory();

                if (daoFactory instanceof JdbcDaoFactory) {
                    Map<String, Long> localChannelIds = new HashMap<String, Long>();
                    DonkeyDao dao = daoFactory.getDao();
                    try {
                        localChannelIds = dao.getLocalChannelIds();
                    } finally {
                        if (dao != null) {
                            dao.close();
                        }
                    }

                    Map<String, Long> channelsToIndex = new HashMap<String, Long>();
                    Map<String, String> affectedChannels = new HashMap<String, String>();

                    SqlSession session = SqlConfig.getSqlSessionManager().openSession();

                    try {
                        Connection connection = session.getConnection();

                        for (Entry<String, Long> entry : localChannelIds.entrySet()) {
                            String channelId = entry.getKey();
                            long localChannelId = entry.getValue();
                            String tableName = "D_MM" + localChannelId;
                            String indexName = tableName + "_INDEX3";

                            if (!DatabaseUtil.indexExists(connection, tableName, indexName)) {
                                channelsToIndex.put(channelId, localChannelId);
                                affectedChannels.put(channelId, getChannelName(channelId));
                            }
                        }
                    } finally {
                        session.close();
                    }

                    taskReadWriteLock.writeLock().lock();
                    try {
                        currentTask.setAffectedChannels(new HashMap<String, String>(affectedChannels));
                    } finally {
                        taskReadWriteLock.writeLock().unlock();
                    }

                    class ChannelStoppedException extends Exception {
                    }

                    class AddIndexChannelTaskHandler extends ChannelTaskHandler {

                        private Map<String, String> affectedChannels;

                        public AddIndexChannelTaskHandler(Map<String, String> affectedChannels) {
                            this.affectedChannels = affectedChannels;
                        }

                        @Override
                        public void taskCompleted(String channelId, Integer metaDataId) {
                            affectedChannels.remove(channelId);

                            taskReadWriteLock.writeLock().lock();
                            try {
                                currentTask.setAffectedChannels(new HashMap<String, String>(affectedChannels));
                            } finally {
                                taskReadWriteLock.writeLock().unlock();
                            }
                        }

                        @Override
                        public void taskErrored(String channelId, Integer metaDataId, Exception e) {
                            if (!(e instanceof ChannelStoppedException)) {
                                logger.error("Unable to add index to channel " + channelId + ".", e);
                            }
                        }

                        @Override
                        public void taskCancelled(String channelId, Integer metaDataId,
                                CancellationException e) {
                            logger.error("Unable to add index to channel " + channelId + ".", e);
                        }
                    }

                    AddIndexChannelTaskHandler taskHandler = new AddIndexChannelTaskHandler(affectedChannels);
                    final QuerySource querySource = ((JdbcDaoFactory) daoFactory).getQuerySource();

                    for (Entry<String, Long> entry : channelsToIndex.entrySet()) {
                        if (isCancelled()) {
                            break;
                        }

                        final String channelId = entry.getKey();
                        final long localChannelId = entry.getValue();
                        final String tableName = "D_MM" + localChannelId;
                        final String indexName = tableName + "_INDEX3";

                        ChannelTask addIndexTask = new ChannelTask(channelId) {
                            @Override
                            public Void execute() throws Exception {
                                Channel channel = engineController.getDeployedChannel(channelId);
                                if (channel != null && channel.getCurrentState() != DeployedState.STOPPED) {
                                    throw new ChannelStoppedException();
                                }

                                Map<String, Object> values = new HashMap<String, Object>();
                                values.put("localChannelId", localChannelId);
                                String query = querySource.getQuery("createConnectorMessageTableIndex3",
                                        values);

                                if (query != null) {
                                    logger.debug("Adding index " + indexName + " on table " + tableName + ".");
                                    executeUpdate(query);
                                } else {
                                    throw new Exception(
                                            "Error adding index: Update statement not found for database type: "
                                                    + Donkey.getInstance().getConfiguration()
                                                            .getDonkeyProperties().getProperty("database"));
                                }

                                return null;
                            }
                        };

                        List<ChannelFuture> futures = engineController
                                .submitTasks(Collections.singletonList(addIndexTask), taskHandler);

                        if (futures.size() > 0) {
                            futures.get(0).get();
                        }
                    }

                    int totalCount = channelsToIndex.size();
                    int successCount = totalCount - affectedChannels.size();
                    return "<html>" + successCount + " out of " + channelsToIndex.size()
                            + " indices successfully added.</html>";
                } else {
                    throw new Exception("Unable to perform task: DAO type is not JDBC.");
                }
            } else {
                throw new Exception("Unknown task ID: " + taskId);
            }
        } finally {
            stopTask();
        }
    } else {
        throw new Exception("Another database task is already running: " + databaseTask.getName());
    }
}

From source file:com.mirth.connect.server.controllers.DefaultDatabaseTaskController.java

License:Open Source License

private void executeUpdate(String sql) throws SQLException {
    SqlSession session = SqlConfig.getSqlSessionManager().openSession();
    try {/*from www.  j a  v  a2  s. c o m*/
        session.getConnection().createStatement().executeUpdate(sql);
    } finally {
        session.close();
    }
}

From source file:com.qcloud.component.snaker.access.mybatis.MybatisAccess.java

License:Open Source License

/**
 * JDBC?BLOB/* www  . j a  v  a2s .  c o m*/
 */
public void saveProcess(Process process) {

    super.saveProcess(process);
    SqlSession sqlSession = getSession();
    if (process.getBytes() != null) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = sqlSession.getConnection();
            pstmt = conn.prepareStatement(PROCESS_UPDATE_BLOB);
            pstmt.setBytes(1, process.getBytes());
            pstmt.setString(2, process.getId());
            pstmt.execute();
        } catch (Exception e) {
            throw new SnakerException(e.getMessage(), e.getCause());
        } finally {
            try {
                JdbcHelper.close(pstmt);
                SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
            } catch (SQLException e) {
                throw new SnakerException(e.getMessage(), e.getCause());
            }
        }
    }
}

From source file:com.qcloud.component.snaker.access.mybatis.MybatisAccess.java

License:Open Source License

/**
 * JDBC?BLOB//from   w w  w. j  a v a2s .  co m
 */
public void updateProcess(Process process) {

    super.updateProcess(process);
    SqlSession sqlSession = getSession();
    if (process.getBytes() != null) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = sqlSession.getConnection();
            pstmt = conn.prepareStatement(PROCESS_UPDATE_BLOB);
            pstmt.setBytes(1, process.getBytes());
            pstmt.setString(2, process.getId());
            pstmt.execute();
        } catch (Exception e) {
            throw new SnakerException(e.getMessage(), e.getCause());
        } finally {
            try {
                JdbcHelper.close(pstmt);
                SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
            } catch (SQLException e) {
                throw new SnakerException(e.getMessage(), e.getCause());
            }
        }
    }
}

From source file:com.qcloud.component.snaker.access.mybatis.MybatisAccess.java

License:Open Source License

/**
 * //from  w ww. ja v a  2s.  com
 * @param column ?
 * @param sql sql?
 * @param params ?
 * @return 
 */
public Object query(int column, String sql, Object... params) {

    SqlSession sqlSession = getSession();
    Object result;
    try {
        if (log.isDebugEnabled()) {
            log.debug("??=\n" + sql);
        }
        result = runner.query(sqlSession.getConnection(), sql, new ScalarHandler(column), params);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
    }
    return result;
}

From source file:com.qcloud.component.snaker.access.mybatis.MybatisAccess.java

License:Open Source License

public void saveOrUpdate(Map<String, Object> map) {

    SqlSession sqlSession = getSession();
    String sql = (String) map.get(KEY_SQL);
    Object[] args = (Object[]) map.get(KEY_ARGS);
    try {/*from  w w w.  ja va 2  s.  c  om*/
        if (log.isDebugEnabled()) {
            log.debug("?(??)=\n" + sql);
        }
        runner.update(sqlSession.getConnection(), sql, args);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
    }
}

From source file:com.qcloud.component.snaker.access.mybatis.MybatisAccess.java

License:Open Source License

public <T> T queryObject(Class<T> clazz, String sql, Object... args) {

    SqlSession sqlSession = getSession();
    List<T> result = null;/*www  . ja  v a  2s .  c  om*/
    try {
        if (log.isDebugEnabled()) {
            log.debug("??=\n" + sql);
        }
        result = runner.query(sqlSession.getConnection(), sql, new BeanPropertyHandler<T>(clazz), args);
        return JdbcHelper.requiredSingleResult(result);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw new SnakerException(e.getMessage(), e.getCause());
    } finally {
        SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
    }
}

From source file:com.qcloud.component.snaker.access.mybatis.MybatisAccess.java

License:Open Source License

public <T> List<T> queryList(Class<T> clazz, String sql, Object... args) {

    SqlSession sqlSession = getSession();
    try {//from w w  w. j  a v  a 2 s  . c  om
        if (log.isDebugEnabled()) {
            log.debug("?=\n" + sql);
        }
        return runner.query(sqlSession.getConnection(), sql, new BeanPropertyHandler<T>(clazz), args);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw new SnakerException(e.getMessage(), e.getCause());
    } finally {
        SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
    }
}

From source file:com.qwazr.library.mybatis.MybatisTest.java

License:Apache License

private void checkSession(SqlSessionFactory sessionFactory) throws SQLException {
    Assert.assertNotNull(sessionFactory);
    final SqlSession session = sessionFactory.openSession();
    try (final Connection connection = session.getConnection()) {
        Assert.assertNotNull(connection);
    }//from  ww  w . j  a  v  a  2  s .co  m
}