Example usage for org.apache.ibatis.session SqlSessionFactory openSession

List of usage examples for org.apache.ibatis.session SqlSessionFactory openSession

Introduction

In this page you can find the example usage for org.apache.ibatis.session SqlSessionFactory openSession.

Prototype

SqlSession openSession(ExecutorType execType, Connection connection);

Source Link

Usage

From source file:com.beginner.core.dao.DaoSupport.java

License:Apache License

/** 
 * {@inheritDoc}//  w  w w  . ja  va 2  s .c o m
 */
@Override
public void batchSave(String str, List objs) throws Exception {
    SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
    //?
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    try {
        if (objs != null) {
            for (int i = 0, size = objs.size(); i < size; i++) {
                sqlSession.insert(str, objs.get(i));
            }
            sqlSession.flushStatements();
            sqlSession.commit();
            sqlSession.clearCache();
        }
    } finally {
        sqlSession.close();
    }
}

From source file:com.beginner.core.dao.DaoSupport.java

License:Apache License

/** 
 * {@inheritDoc}//w ww .  j ava 2s  . c  o  m
 */
@Override
public void batchUpdate(String str, List objs) throws Exception {
    SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
    //?
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    try {
        if (objs != null) {
            for (int i = 0, size = objs.size(); i < size; i++) {
                sqlSession.update(str, objs.get(i));
            }
            sqlSession.flushStatements();
            sqlSession.commit();
            sqlSession.clearCache();
        }
    } finally {
        sqlSession.close();
    }
}

From source file:com.beginner.core.dao.DaoSupport.java

License:Apache License

/** 
 * {@inheritDoc}//w  w  w . j ava 2  s .c om
 */
@Override
public void batchDelete(String str, List objs) throws Exception {
    SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
    //?
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    try {
        if (objs != null) {
            for (int i = 0, size = objs.size(); i < size; i++) {
                sqlSession.delete(str, objs.get(i));
            }
            sqlSession.flushStatements();
            sqlSession.commit();
            sqlSession.clearCache();
        }
    } finally {
        sqlSession.close();
    }
}

From source file:com.glaf.core.test.MyBatisBatchTest.java

License:Apache License

@Test
public void testInsert() {
    SqlSessionFactory sqlSessionFactory = super.getBean("sqlSessionFactory");
    SqlSession sqlSession = null;/*  www  .j av  a 2 s  .co m*/
    try {
        sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        long id = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            SysLog log = new SysLog();
            log.setId(id + i);
            log.setAccount("test");
            log.setCreateTime(new Date());
            log.setIp("192.168.0.12");
            log.setOperate("insert");
            log.setContent("Test Insert");
            sqlSession.insert("insertSysLog", log);
            if (i == 9999) {
                // throw new RuntimeException("throw exception");
            }
        }
        sqlSession.commit();
    } catch (Exception ex) {
        if (sqlSession != null) {
            sqlSession.rollback();
        }
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}

From source file:com.glaf.core.test.MyBatisBatchTest2.java

License:Apache License

@Test
public void testInsert() {
    SqlSessionFactory sqlSessionFactory = super.getBean("sqlSessionFactory");
    SqlSession sqlSession = null;/*from www.j a v  a 2  s .co m*/
    try {
        Environment.setCurrentSystemName("wechat");
        HibernateBeanFactory.reload();
        sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        long id = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            SysLog log = new SysLog();
            log.setId(id + i);
            log.setAccount("test");
            log.setCreateTime(new Date());
            log.setIp("192.168.0.12");
            log.setOperate("insert");
            log.setContent("Test Insert");
            sqlSession.insert("insertSysLog", log);
            if (i == 999) {
                // throw new RuntimeException("throw exception");
            }
        }
        sqlSession.commit();
    } catch (Exception ex) {
        if (sqlSession != null) {
            sqlSession.rollback();
        }
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}

From source file:com.luxoft.mybatis.splitter.UpdateSplitterPluginTest.java

License:Apache License

@Test
public void mockTest() throws IOException, SQLException {
    expect(connection.getAutoCommit()).andStubReturn(false);
    expect(connection.prepareStatement("insert into test values(?)")).andReturn(statement);
    statement.setString(1, "first");
    statement.addBatch();//from  w w  w  . j  a v a  2  s  . co m
    statement.setString(1, "second");
    statement.addBatch();
    statement.setString(1, "third");
    statement.addBatch();
    expect(statement.executeBatch()).andStubReturn(new int[] { 1 });
    statement.close();
    connection.setAutoCommit(true);
    connection.rollback();
    connection.close();

    replay();

    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
            .build(Resources.getResourceAsStream("configuration.xml"));
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, connection);
    doInsert(sqlSession);
    sqlSession.close();
}

From source file:com.ocean.ddl.mybatis.util.SqlSessionUtils.java

License:Apache License

/**
 * If a Spring transaction is active it uses {@code DataSourceUtils} to get
 * a Spring managed {@code Connection}, then creates a new
 * {@code SqlSession} with this connection and synchronizes it with the
 * transaction. If there is not an active transaction it gets a connection
 * directly from the {@code DataSource} and creates a {@code SqlSession}
 * with it./*from   w  w  w. jav  a 2s  .  c o m*/
 * 
 * @param sessionFactory
 *            a MyBatis {@code SqlSessionFactory} to create new sessions
 * @param executorType
 *            The executor type of the SqlSession to create
 * @param exceptionTranslator
 *            Optional. Translates SqlSession.commit() exceptions to Spring
 *            exceptions.
 * @throws TransientDataAccessResourceException
 *             if a transaction is active and the {@code SqlSessionFactory}
 *             is not using a {@code SpringManagedTransactionFactory}
 * @see SpringManagedTransactionFactory
 */
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator) {

    Assert.notNull(sessionFactory, "No SqlSessionFactory specified");
    Assert.notNull(executorType, "No ExecutorType specified");

    SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);

    if (holder != null && holder.isSynchronizedWithTransaction()) {
        if (holder.getExecutorType() != executorType) {
            throw new TransientDataAccessResourceException(
                    "Cannot change the ExecutorType when there is an existing transaction");
        }

        holder.requested();

        if (logger.isDebugEnabled()) {
            logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
        }

        return holder.getSqlSession();
    }

    DataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource();

    // SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but
    // we keep this check for the case that SqlSessionUtils is called from
    // custom code
    boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
    Connection conn;
    try {
        conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource);
    } catch (SQLException e) {
        throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]");
    }

    // Assume either DataSourceTransactionManager or the underlying
    // connection pool already dealt with enabling auto commit.
    // This may not be a good assumption, but the overhead of checking
    // connection.getAutoCommit() again may be expensive (?) in some drivers
    // (see DataSourceTransactionManager.doBegin()). One option would be to
    // only check for auto commit if this function is being called outside
    // of DSTxMgr, but to do that we would need to be able to call
    // ConnectionHolder.isTransactionActive(), which is protected and not
    // visible to this class.
    SqlSession session = sessionFactory.openSession(executorType, conn);

    // Register session holder and bind it to enable synchronization.
    //
    // Note: The DataSource should be synchronized with the transaction
    // either through DataSourceTxMgr or another tx synchronization.
    // Further assume that if an exception is thrown, whatever started the
    // transaction will
    // handle closing / rolling back the Connection associated with the
    // SqlSession.
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        if (!(sessionFactory.getConfiguration().getEnvironment()
                .getTransactionFactory() instanceof SpringManagedTransactionFactory)
                && DataSourceUtils.isConnectionTransactional(conn, dataSource)) {
            throw new TransientDataAccessResourceException(
                    "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Registering transaction synchronization for SqlSession [" + session + "]");
        }
        holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
        TransactionSynchronizationManager.bindResource(sessionFactory, holder);
        TransactionSynchronizationManager
                .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
        holder.setSynchronizedWithTransaction(true);
        holder.requested();
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("SqlSession [" + session
                    + "] was not registered for synchronization because synchronization is not active");
        }
    }

    return session;
}