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

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

Introduction

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

Prototype

void rollback();

Source Link

Document

Discards pending batch statements and rolls database connection back.

Usage

From source file:org.apache.camel.component.mybatis.DefaultMyBatisProcessingStrategy.java

License:Apache License

public List<?> poll(MyBatisConsumer consumer, MyBatisEndpoint endpoint) throws Exception {
    SqlSession session = endpoint.getSqlSessionFactory().openSession();
    try {//w ww .java  2  s.c  o  m
        List<Object> objects = session.selectList(endpoint.getStatement(), null);
        session.commit();
        return objects;
    } catch (Exception e) {
        session.rollback();
        throw e;
    } finally {
        session.close();
    }
}

From source file:org.apache.camel.component.mybatis.MyBatisProducer.java

License:Apache License

public void process(Exchange exchange) throws Exception {
    SqlSession session;

    ExecutorType executorType = endpoint.getExecutorType();
    if (executorType == null) {
        session = endpoint.getSqlSessionFactory().openSession();
    } else {/*from ww w. j  a v  a 2  s  . c o m*/
        session = endpoint.getSqlSessionFactory().openSession(executorType);
    }

    try {
        switch (endpoint.getStatementType()) {
        case SelectOne:
            doSelectOne(exchange, session);
            break;
        case SelectList:
            doSelectList(exchange, session);
            break;
        case Insert:
            doInsert(exchange, session);
            break;
        case InsertList:
            doInsertList(exchange, session);
            break;
        case Update:
            doUpdate(exchange, session);
            break;
        case UpdateList:
            doUpdateList(exchange, session);
            break;
        case Delete:
            doDelete(exchange, session);
            break;
        case DeleteList:
            doDeleteList(exchange, session);
            break;
        default:
            throw new IllegalArgumentException("Unsupported statementType: " + endpoint.getStatementType());
        }
        // flush the batch statements and commit the database connection
        session.commit();
    } catch (Exception e) {
        // discard the pending batch statements and roll the database connection back
        session.rollback();
        throw e;
    } finally {
        // and finally close the session as we're done
        session.close();
    }
}

From source file:org.camunda.bpm.engine.test.standalone.initialization.ProcessEngineInitializationTest.java

License:Apache License

public void testVersionMismatch() {
    // first create the schema
    ProcessEngineImpl processEngine = (ProcessEngineImpl) ProcessEngineConfiguration
            .createProcessEngineConfigurationFromResource(
                    "org/camunda/bpm/engine/test/standalone/initialization/notables.camunda.cfg.xml")
            .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_CREATE_DROP)
            .buildProcessEngine();/*from  w ww. ja v  a  2  s.  c om*/

    // then update the version to something that is different to the library
    // version
    DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) processEngine
            .getProcessEngineConfiguration().getSessionFactories().get(DbSqlSession.class);
    SqlSessionFactory sqlSessionFactory = dbSqlSessionFactory.getSqlSessionFactory();
    SqlSession sqlSession = sqlSessionFactory.openSession();
    boolean success = false;
    try {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", "schema.version");
        parameters.put("value", "25.7");
        parameters.put("revision", new Integer(1));
        parameters.put("newRevision", new Integer(2));
        sqlSession.update("updateProperty", parameters);
        success = true;
    } catch (Exception e) {
        throw new ProcessEngineException("couldn't update db schema version", e);
    } finally {
        if (success) {
            sqlSession.commit();
        } else {
            sqlSession.rollback();
        }
        sqlSession.close();
    }

    try {
        // now we can see what happens if when a process engine is being
        // build with a version mismatch between library and db tables
        ProcessEngineConfiguration
                .createProcessEngineConfigurationFromResource(
                        "org/camunda/bpm/engine/test/standalone/initialization/notables.camunda.cfg.xml")
                .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_FALSE)
                .buildProcessEngine();

        fail("expected exception");
    } catch (WrongDbException e) {
        assertTextPresent("version mismatch", e.getMessage());
        assertEquals("25.7", e.getDbVersion());
        assertEquals(ProcessEngine.VERSION, e.getLibraryVersion());
    }

    // closing the original process engine to drop the db tables
    processEngine.close();
}

From source file:org.flowable.standalone.initialization.ProcessEngineInitializationTest.java

License:Apache License

public void testVersionMismatch() {
    // first create the schema
    ProcessEngineImpl processEngine = (ProcessEngineImpl) ProcessEngineConfiguration
            .createProcessEngineConfigurationFromResource(
                    "org/flowable/standalone/initialization/notables.flowable.cfg.xml")
            .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_CREATE_DROP)
            .buildProcessEngine();//from   w w w.j ava  2s  .  com

    // then update the version to something that is different to the library
    // version
    DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) processEngine
            .getProcessEngineConfiguration().getSessionFactories().get(DbSqlSession.class);
    SqlSessionFactory sqlSessionFactory = dbSqlSessionFactory.getSqlSessionFactory();
    SqlSession sqlSession = sqlSessionFactory.openSession();
    boolean success = false;
    try {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", "schema.version");
        parameters.put("value", "25.7");
        parameters.put("revision", 1);
        parameters.put("newRevision", 2);
        sqlSession.update("updateProperty", parameters);
        success = true;
    } catch (Exception e) {
        throw new FlowableException("couldn't update db schema version", e);
    } finally {
        if (success) {
            sqlSession.commit();
        } else {
            sqlSession.rollback();
        }
        sqlSession.close();
    }

    try {
        // now we can see what happens if when a process engine is being
        // build with a version mismatch between library and db tables
        ProcessEngineConfiguration
                .createProcessEngineConfigurationFromResource(
                        "org/flowable/standalone/initialization/notables.flowable.cfg.xml")
                .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_FALSE)
                .buildProcessEngine();

        fail("expected exception");
    } catch (FlowableWrongDbException e) {
        assertTextPresent("version mismatch", e.getMessage());
        assertEquals("25.7", e.getDbVersion());
        assertEquals(ProcessEngine.VERSION, e.getLibraryVersion());
    }

    // closing the original process engine to drop the db tables
    processEngine.close();
}

From source file:org.mule.module.mybatis.MyBatisConnector.java

License:CPAL v1.0

/**
 * Rollbacks and closes the current transaction
 * /*  w  ww  . j ava2s .  co m*/
 * {@sample.xml ../../../doc/mule-mybatis-module.xml.sample mybatis:rollback-transaction}
 * 
 * @throws IOException Io Error
 */
@Processor
public void rollbackTransaction() throws IOException {
    SqlSession sqlSession = threadLocalSession.get();
    sqlSession.rollback();
    sqlSession.close();
    threadLocalSession.set(null);
}

From source file:org.mybatis.guice.session.DbSessionManager.java

License:Apache License

public void rollback() {
    final SqlSession sqlSession = localSqlSession.get();
    if (sqlSession == null)
        throw new SqlSessionException("Error:  Cannot rollback.  No managed session is started.");
    sqlSession.rollback();
}

From source file:org.snaker.engine.access.transaction.MybatisTransactionInterceptor.java

License:Apache License

@Override
protected void rollback(TransactionStatus status) {
    SqlSession session = (SqlSession) status.getTransaction();
    if (session != null) {
        try {/*from   www  . j  a va 2s. co  m*/
            if (log.isInfoEnabled()) {
                log.info("rollback transaction=" + session.hashCode());
            }
            session.rollback();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            session.close();
            TransactionObjectHolder.unbind();
        }
    }
}

From source file:org.sonar.core.persistence.SemaphoreDao.java

License:Open Source License

/**
 * Insert the semaphore and commit. Rollback and return null if the semaphore already exists in db (whatever
 * the lock date)/* w  w w.j av  a  2  s. co m*/
 */
@CheckForNull
private SemaphoreDto tryToInsert(String name, Date lockedNow, SqlSession session) {
    try {
        SemaphoreMapper mapper = session.getMapper(SemaphoreMapper.class);
        SemaphoreDto semaphore = new SemaphoreDto().setName(name).setLockedAt(lockedNow);
        mapper.initialize(semaphore);
        session.commit();
        return semaphore;
    } catch (Exception e) {
        // probably because of the semaphore already exists in db
        session.rollback();
        return null;
    }
}

From source file:org.sonar.core.resource.ResourceDaoTest.java

License:Open Source License

@Test
public void should_insert_using_existing_session() throws Exception {
    setupData("insert");

    ResourceDto file1 = new ResourceDto().setUuid("ABCD")
            .setKey("org.struts:struts:/src/main/java/org/struts/Action.java")
            .setDeprecatedKey("org.struts:struts:org.struts.Action").setScope(Scopes.FILE)
            .setQualifier(Qualifiers.FILE).setLanguage("java").setName("Action")
            .setLongName("org.struts.Action");
    ResourceDto file2 = new ResourceDto().setUuid("BCDE")
            .setKey("org.struts:struts:/src/main/java/org/struts/Filter.java")
            .setDeprecatedKey("org.struts:struts:org.struts.Filter").setScope(Scopes.FILE)
            .setQualifier(Qualifiers.FILE).setLanguage("java").setName("Filter")
            .setLongName("org.struts.Filter");

    SqlSession session = getMyBatis().openSession();

    dao.insertUsingExistingSession(file1, session);
    dao.insertUsingExistingSession(file2, session);

    session.rollback();

    assertEmptyTables("projects");
}

From source file:ph.fingra.hadoop.dbms.parts.component.service.ComponentAppversionServiceImpl.java

License:Apache License

public int insertBatchComponentAppversionDay(List<CompoAppversionAll> in_volist) throws Exception {

    if (in_volist == null) {
        return 0;
    }/*from w  w  w.ja v  a  2  s .c o m*/

    SqlSession session = ConnectionFactory.getSession().openSession(ExecutorType.BATCH, false);
    ComponentAppversionDao dao = session.getMapper(ComponentAppversionDao.class);

    boolean has_error = false;

    try {

        if (in_volist != null) {

            Iterator<CompoAppversionAll> it = in_volist.iterator();

            while (it.hasNext()) {
                CompoAppversionAll insert = it.next();
                dao.insertCompoAppversionDay(insert);
            }
        }

        List<BatchResult> results = session.flushStatements();
        results.clear();
    } catch (Exception e) {
        has_error = true;
        session.rollback();
        session.close();
        throw e;
    } finally {
        if (has_error == false)
            session.commit();
        session.close();
    }

    return (has_error == false) ? 1 : 0;
}