Example usage for org.apache.ibatis.session ExecutorType BATCH

List of usage examples for org.apache.ibatis.session ExecutorType BATCH

Introduction

In this page you can find the example usage for org.apache.ibatis.session ExecutorType BATCH.

Prototype

ExecutorType BATCH

To view the source code for org.apache.ibatis.session ExecutorType BATCH.

Click Source Link

Usage

From source file:cern.c2mon.server.history.dao.LoggerDAO.java

License:Open Source License

/**
 * Inserts into the database a set of rows containing the data coming in
 * several IFallback objects/*from   w w w  . j av a  2 s .c  o m*/
 *
 * @param data
 *          List of IFallback object whose data has to be inserted in the DB
 * @throws IDBPersistenceException
 *           An exception is thrown in case an error occurs during the data
 *           insertion. The exception provides also the number of already
 *           committed objects
 */
@SuppressWarnings("unchecked")
// add generics to persistence manager
public final void storeData(final List data) throws IDBPersistenceException {
    SqlSession session = null;
    int size = data.size();
    int commited = 0;
    T tag;

    try {
        // We use batch set of statements to improve performance
        session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Obtained batch transacted SQL session (session: " + session.toString() + ")");
        }
        LoggerMapper<T> persistenceMapper = session.getMapper(mapperInterface);

        // Iterate through the list of DataTagCacheObjects to insert
        // them one by one
        for (int i = 0; i != size; i++) {
            if ((0 == i % RECORDS_PER_BATCH) && i > 0) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("storeData([Collection]) : Commiting rows for i=" + i);
                }
                session.commit();
                commited = i;
            }

            if (data.get(i) != null) {
                tag = (T) data.get(i);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Logging object with ID: " + tag.getId());
                }
                persistenceMapper.insertLog(tag);
            }
        }
        // Commit the transaction
        session.commit();
        commited = size;
    } catch (PersistenceException e) {
        LOGGER.error("storeData([Collection]) : Error executing/closing prepared statement for " + data.size()
                + " dataTags", e);
        try {
            if (session != null) {
                session.rollback();
            }
        } catch (Exception sql) {
            LOGGER.error("storeData([Collection]) : Error rolling back transaction.", sql);
        }
        throw new IDBPersistenceException(e.getMessage(), commited);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception e) {
            LOGGER.error("storeData([Collection]) : Error closing session.", e);
        }
    }
}

From source file:cn.cuizuoli.appranking.service.AppRankingService.java

License:Apache License

/**
 * batchAdd/*from   w w w . ja v  a  2s. c  o m*/
 * @param appRankingList
 */
@Transactional
public void batchAdd(List<AppRanking> appRankingList) {
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    AppRankingRepository batchAppRankingRepository = sqlSession.getMapper(AppRankingRepository.class);
    int i = 1;
    for (AppRanking appRanking : appRankingList) {
        appRanking.setId(appRankingIncrementer.nextStringValue());
        appRanking.setDateHour(DateTime.now().toString("yyyyMMddHH"));
        batchAppRankingRepository.insert(appRanking);
        if (i % 100 == 0) {
            sqlSession.commit();
        }
        i++;
    }
    sqlSession.commit();
    sqlSession.close();
}

From source file:com.baomidou.framework.service.impl.ServiceImpl.java

License:Apache License

/**
 * ??/*  w ww.ja v a  2  s. co  m*/
 *
 * @param entityList
 * @param batchSize
 * @return
 */
public boolean insertBatch(List<T> entityList, int batchSize) {
    if (CollectionUtil.isEmpty(entityList)) {
        throw new IllegalArgumentException("Error: entityList must not be empty");
    }
    TableInfo tableInfo = TableInfoHelper.getTableInfo(currentModleClass());
    if (null == tableInfo) {
        throw new MybatisPlusException("Error: Cannot execute insertBatch Method, ClassGenricType not found .");
    }
    SqlSession batchSqlSession = tableInfo.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
    try {
        int size = entityList.size();
        for (int i = 0; i < size; i++) {
            baseMapper.insert(entityList.get(i));
            if (i % batchSize == 0) {
                batchSqlSession.flushStatements();
            }
        }
        batchSqlSession.flushStatements();
    } catch (Exception e) {
        logger.warning("Error: Cannot execute insertBatch Method. Cause:" + e);
        return false;
    }
    return true;

}

From source file:com.baomidou.mybatisplus.activerecord.Record.java

License:Apache License

/**
 * <p>//from  w  w w.  j  ava  2 s.  c o  m
 * ?? SqlSession
 * </p>
 * 
 * @param clazz
 *            
 * @return SqlSession
 */
public static SqlSession sqlSessionBatch(Class<?> clazz) {
    return GlobalConfiguration.currentSessionFactory(clazz).openSession(ExecutorType.BATCH, false);
}

From source file:com.baomidou.mybatisplus.mapper.SqlHelper.java

License:Apache License

/**
 * <p>/*from   ww w. java 2s  . c o m*/
 * ?? SqlSession
 * </p>
 *
 * @param clazz 
 * @return SqlSession
 */
public static SqlSession sqlSessionBatch(Class<?> clazz) {
    return GlobalConfiguration.currentSessionFactory(clazz).openSession(ExecutorType.BATCH);
}

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

License:Apache License

/** 
 * {@inheritDoc}// ww  w . ja  va2  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}/*from  w  ww  . j a  va 2  s. 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}//from w ww  .j  a  v a 2 s.  c o m
 */
@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.dmm.framework.basedb.apache.ibatis.session.Configuration.java

License:Apache License

public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;/*from   ww w.  j  a  va2  s . c  o  m*/
    if (ExecutorType.BATCH == executorType) {
        executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
        executor = new ReuseExecutor(this, transaction);
    } else {
        executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
        executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}

From source file:com.glaf.core.db.TableDataManager.java

License:Apache License

public Collection<TableModel> insertAll(String systemName, TableDefinition tableDefinition, String seqNo,
        Collection<TableModel> rows) {
    com.glaf.core.config.Environment.setCurrentSystemName(systemName);
    logger.debug("tableDefinition=" + tableDefinition);
    logger.debug("idColumn=" + tableDefinition.getIdColumn().toString());
    if (tableDefinition.getTableName() != null) {
        tableDefinition.setTableName(tableDefinition.getTableName().toUpperCase());
    }//from   www . j  av  a 2  s.  c  o m
    Map<String, Object> colMap = new java.util.HashMap<String, Object>();

    Map<String, String> exprMap = new java.util.HashMap<String, String>();
    List<ColumnDefinition> exprColumns = new java.util.ArrayList<ColumnDefinition>();

    ColumnModel idColumn = new ColumnModel();

    ColumnDefinition idCol = tableDefinition.getIdColumn();
    if (idCol != null && idCol.getColumnName() != null) {
        idColumn.setColumnName(idCol.getColumnName());
        idColumn.setJavaType(idCol.getJavaType());
        idColumn.setValueExpression(idCol.getValueExpression());
        exprColumns.add(idCol);
        exprMap.put(idCol.getColumnName().toLowerCase(), idCol.getValueExpression());
    }

    Iterator<ColumnDefinition> iter = tableDefinition.getColumns().iterator();
    while (iter.hasNext()) {
        ColumnDefinition cell = iter.next();
        if (StringUtils.isNotEmpty(cell.getValueExpression())) {
            exprMap.put(cell.getColumnName().toLowerCase(), cell.getValueExpression());
            exprColumns.add(cell);
        }
    }

    logger.debug("expr map:" + exprMap);

    List<TableModel> inertRows = new java.util.ArrayList<TableModel>();

    logger.debug(" rows size = " + rows.size());
    // logger.debug(" key map: " + keyMap);
    Iterator<TableModel> iterator = rows.iterator();
    while (iterator.hasNext()) {
        TableModel tableData = iterator.next();
        ColumnModel myPK = tableData.getIdColumn();
        ColumnModel pkColumn = new ColumnModel();
        pkColumn.setColumnName(idColumn.getColumnName());
        pkColumn.setJavaType(idColumn.getJavaType());

        for (ColumnModel column : tableData.getColumns()) {
            colMap.put(column.getColumnName(), column.getValue());
        }

        for (ColumnDefinition c : exprColumns) {
            ColumnModel x = new ColumnModel();
            x.setColumnName(c.getColumnName());
            x.setJavaType(c.getJavaType());
            x.setValueExpression(c.getValueExpression());
            tableData.addColumn(x);
        }

        for (ColumnModel cell : tableData.getColumns()) {
            String expr = exprMap.get(cell.getColumnName().toLowerCase());
            if (StringUtils.isNotEmpty(expr)) {
                if (ExpressionConstants.NOW_EXPRESSION.equals(expr)
                        || ExpressionConstants.CURRENT_YYYYMMDD_EXPRESSION.equals(expr)) {
                    if (cell.getDateValue() == null) {
                        cell.setDateValue(new Date());
                        cell.setValue(cell.getDateValue());
                    }
                }
                if (ExpressionConstants.ID_EXPRESSION.equals(expr)) {
                    if (cell.getValue() == null) {
                        if (StringUtils.equals(cell.getJavaType(), "Integer")) {
                            cell.setValue(getEntityService().nextId().intValue());
                        } else if (StringUtils.equals(cell.getJavaType(), "Long")) {
                            cell.setValue(getEntityService().nextId());
                        } else {
                            cell.setValue(getEntityService().getNextId());
                        }
                    }
                }
                if (ExpressionConstants.SEQNO_EXPRESSION.equals(expr)) {
                    cell.setValue(seqNo);
                }
                if (ExpressionConstants.UUID_EXPRESSION.equals(expr)) {
                    cell.setValue(UUID32.getUUID());
                }
            }
        }

        if (myPK != null && myPK.getValue() != null) {
            pkColumn.setValue(myPK.getValue());
        } else {
            if (StringUtils.equals(pkColumn.getJavaType(), "Integer")) {
                pkColumn.setValue(getEntityService().nextId().intValue());
                logger.debug("------------int--------------");
            } else if (StringUtils.equals(pkColumn.getJavaType(), "Long")) {
                pkColumn.setValue(getEntityService().nextId());
            } else {
                pkColumn.setValue(getEntityService().getNextId());
            }
        }

        tableData.removeColumn(pkColumn);
        tableData.addColumn(pkColumn);
        tableData.setIdColumn(pkColumn);

        inertRows.add(tableData);
    }

    if (!inertRows.isEmpty()) {
        logger.debug("inert rows size:" + inertRows.size());
        for (TableModel tableData : inertRows) {
            tableData.setTableName(tableDefinition.getTableName());
            logger.debug(tableData.toString());
            SqlSession sqlSession = null;
            Connection conn = null;
            try {
                conn = DBConnectionFactory.getConnection(systemName);
                conn.setAutoCommit(false);
                sqlSession = getSqlSessionFactory().openSession(ExecutorType.BATCH, conn);
                sqlSession.insert("insertTableData", tableData);
                sqlSession.commit();
                conn.commit();
            } catch (Exception ex) {
                JdbcUtils.rollback(conn);
                logger.error(ex);
                ex.printStackTrace();
                throw new RuntimeException(ex);
            } finally {
                JdbcUtils.close(sqlSession);
                JdbcUtils.close(conn);
            }
        }
    }

    return inertRows;
}