Java Code Examples for com.ibatis.sqlmap.client.SqlMapExecutor

The following examples show how to use com.ibatis.sqlmap.client.SqlMapExecutor. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: AsuraFramework   Source File: BaseIbatisDaoContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 批量删除指定SQL的数据
 * 
 * @author zhangshaobin
 * @created 2012-12-3 下午2:19:55
 *
 * @param sqlId	SQL语句ID
 * @param params	删除数据的参数集合;NOT NULL
 * @return	成功更新的记录数
 */
@Override
public int[] batchDelete(final String sqlId, final List<BaseEntity> params) {
	// 执行回调
	final SqlMapClientCallback<Object> callback = new SqlMapClientCallback<Object>() {
		// 实现回调接口
		@Override
		public Object doInSqlMapClient(final SqlMapExecutor executor) throws SQLException {
			// 开始批处理
			executor.startBatch();
			final int[] rtnDel = new int[params.size()];
			for (int i = 0; i < params.size(); i++) {
				//rtnDel[i] = executor.delete(sqlId, params.get(i));
				rtnDel[i] = executor.delete(sqlId, executeRouter(sqlId, params.get(i)));
			}
			// 执行批处理
			executor.executeBatch();
			return rtnDel;
		}
	};

	return (int[]) getWriteSqlMapClientTemplate().execute(callback);
}
 
Example 2
Source Project: AsuraFramework   Source File: BaseIbatisDaoContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 批量更新指定SQL的数据
 *
 * @author zhangshaobin
 * @created 2012-11-5 下午7:36:32
 *
 * @param sqlId	SQL语句ID
 * @param params	SQL语句中占位符对应的值
 * @return	成功更新的记录数
 */
@Override
public int[] batchUpdate(final String sqlId, final List<? extends BaseEntity> params) {
	// 执行回调
	final SqlMapClientCallback<Object> callback = new SqlMapClientCallback<Object>() {
		// 实现回调接口
		@Override
		public Object doInSqlMapClient(final SqlMapExecutor executor) throws SQLException {
			// 开始批处理
			executor.startBatch();
			final int[] rtnUpd = new int[params.size()];
			for (int i = 0; i < params.size(); i++) {
				//rtnUpd[i] = executor.update(sqlId, params.get(i));
				rtnUpd[i] = executor.update(sqlId, executeRouter(sqlId, params.get(i)));
			}
			// 执行批处理
			executor.executeBatch();
			return rtnUpd;
		}
	};

	return (int[]) getWriteSqlMapClientTemplate().execute(callback);
}
 
Example 3
Source Project: AsuraFramework   Source File: BaseIbatisDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 批量删除指定SQL的数据
 *
 * @author zhangshaobin
 * @created 2012-12-3 下午2:19:55
 *
 * @param sqlId	SQL语句ID
 * @param params	SQL语句中占位符对应的值
 * @return	成功更新的记录数
 */
public int[] batchDelete(final String sqlId, final List<BaseEntity> params) {
	// 执行回调
	SqlMapClientCallback<Object> callback = new SqlMapClientCallback<Object>() {
		// 实现回调接口
		public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
			// 开始批处理
			executor.startBatch();
			int[] rtnDel = new int[params.size()];
			for (int i = 0; i < params.size(); i++) {
				rtnDel[i] = executor.delete(sqlId, params.get(i));
			}
			// 执行批处理
			executor.executeBatch();
			return rtnDel;
		}
	};

	return (int[]) template.execute(callback);
}
 
Example 4
Source Project: AsuraFramework   Source File: BaseIbatisDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 批量更新指定SQL的数据
 *
 * @author zhangshaobin
 * @created 2012-11-5 下午7:36:32
 *
 * @param sqlId	SQL语句ID
 * @param params	SQL语句中占位符对应的值
 * @return	成功更新的记录数
 */
public int[] batchUpdate(final String sqlId, final List<? extends BaseEntity> params) {
	// 执行回调
	SqlMapClientCallback<Object> callback = new SqlMapClientCallback<Object>() {
		// 实现回调接口
		public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
			// 开始批处理
			executor.startBatch();
			int[] rtnUpd = new int[params.size()];
			for (int i = 0; i < params.size(); i++) {
				rtnUpd[i] = executor.update(sqlId, params.get(i));
			}
			// 执行批处理
			executor.executeBatch();
			return rtnUpd;
		}
	};

	return (int[]) template.execute(callback);
}
 
Example 5
Source Project: pinpoint   Source File: SqlMapExecutorTestBase.java    License: Apache License 2.0 6 votes vote down vote up
protected final void testAndVerifyQueryForList(SqlMapExecutor executor) throws Exception {
    final String queryForListId = "queryForListId";
    executor.queryForList(queryForListId);
    executor.queryForList(queryForListId, new Object());
    executor.queryForList(queryForListId, 0, 1);
    executor.queryForList(queryForListId, new Object(), 0, 1);

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    Method queryForList1 = executor.getClass().getDeclaredMethod("queryForList", String.class);
    Method queryForList2 = executor.getClass().getDeclaredMethod("queryForList", String.class, Object.class);
    Method queryForList3 = executor.getClass()
            .getDeclaredMethod("queryForList", String.class, int.class, int.class);
    Method queryForList4 = executor.getClass().getDeclaredMethod("queryForList", String.class, Object.class,
            int.class, int.class);
    verifier.verifyTrace(event("IBATIS", queryForList1, Expectations.cachedArgs(queryForListId)));
    verifier.verifyTrace(event("IBATIS", queryForList2, Expectations.cachedArgs(queryForListId)));
    verifier.verifyTrace(event("IBATIS", queryForList3, Expectations.cachedArgs(queryForListId)));
    verifier.verifyTrace(event("IBATIS", queryForList4, Expectations.cachedArgs(queryForListId)));
}
 
Example 6
/**
 * since {@link CobarSqlMapClientTemplate#execute(SqlMapClientCallback)},
 * {@link CobarSqlMapClientTemplate#executeWithListResult(SqlMapClientCallback)
 * )} and
 * {@link CobarSqlMapClientTemplate#executeWithMapResult(SqlMapClientCallback)
 * )} don't support partitioning behaviors, we can unit test them together
 * and use one of them as their representation.
 */
public void testExecutePrefixMethodsOnCobarSqlMapClientTemplate() {

    getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
        public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
            Follower f = new Follower("fname");
            return executor.insert("com.alibaba.cobar.client.entities.Follower.create", f);
        }
    });

    String confirmSQL = "select name from followers where name='fname'";
    // execute method doesn't support partitioning behavior, so the entity will be inserted into default data source, that's , partition1, not partition2 as the rules state.
    verifyEntityExistenceOnSpecificDataSource(confirmSQL, jt1m);
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt1s);
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt2m);
    verifyEntityNonExistenceOnSpecificDataSource(confirmSQL, jt2s);
}
 
Example 7
Source Project: EserKnife   Source File: IbatisDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Integer batchInsert(final String statementName, final List list) {
    Integer result = Integer.valueOf(0);

    try {
        if (list != null) {
            result = (Integer) this.getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
                public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {

                    executor.startBatch();

                    try {
                        int e = 0;

                        for (int n = list.size(); e < n; ++e) {
                            executor.insert(statementName, list.get(e));
                            if ((e + 1) % 10000 == 0) {
                                executor.executeBatch();
                                executor.startBatch();
                            }
                        }

                        executor.executeBatch();
                        return Integer.valueOf(list.size());
                    } catch (SQLException var5) {
                        executor.executeBatch();
                        throw var5;
                    }
                }
            });
        }

        return result;
    } catch (Exception var5) {
        LOGGER.error("批量插入数据异常", var5);
        throw new FrameworkRuntimeException(var5);
    }
}
 
Example 8
Source Project: EserKnife   Source File: IbatisDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Integer batchUpdate(final String statementName, final List list) {
    Integer result = Integer.valueOf(0);

    try {
        if (list != null) {
            result = (Integer) this.getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
                public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {

                    executor.startBatch();
                    int i = 0;

                    for (int n = list.size(); i < n; ++i) {
                        executor.update(statementName, list.get(i));
                        if ((i + 1) % 10000 == 0) {
                            executor.executeBatch();
                            executor.startBatch();
                        }
                    }

                    executor.executeBatch();
                    return Integer.valueOf(list.size());
                }
            });
        }

        return result;
    } catch (Exception var5) {
        LOGGER.error("批量更新数据异常", var5);
        throw new FrameworkRuntimeException(var5);
    }
}
 
Example 9
Source Project: EserKnife   Source File: IbatisDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Integer batchDelete(final String statementName, final List list) {
    Integer result = Integer.valueOf(0);

    try {
        if (list != null) {
            result = (Integer) this.getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
                public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                    executor.startBatch();
                    int i = 0;

                    for (int n = list.size(); i < n; ++i) {
                        executor.delete(statementName, list.get(i));
                        if (i % 10000 == 0) {
                            executor.executeBatch();
                            executor.startBatch();
                        }
                    }

                    executor.executeBatch();
                    return Integer.valueOf(list.size());
                }
            });
        }

        return result;
    } catch (Exception var5) {
        LOGGER.error("批量删除数据异常", var5);
        throw new FrameworkRuntimeException(var5);
    }
}
 
Example 10
Source Project: pinpoint   Source File: SqlMapExecutorTestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected final void testAndVerifyQueryForMap(SqlMapExecutor executor) throws Exception {
    final String queryForMapId = "queryForMapId";
    executor.queryForMap(queryForMapId, new Object(), "key");
    executor.queryForMap(queryForMapId, new Object(), "key", "value");

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    Method queryForMap1 = executor.getClass().getDeclaredMethod("queryForMap", String.class, Object.class,
            String.class);
    Method queryForMap2 = executor.getClass().getDeclaredMethod("queryForMap", String.class, Object.class,
            String.class, String.class);
    verifier.verifyTrace(event("IBATIS", queryForMap1, Expectations.cachedArgs(queryForMapId)));
    verifier.verifyTrace(event("IBATIS", queryForMap2, Expectations.cachedArgs(queryForMapId)));
}
 
Example 11
Source Project: pinpoint   Source File: SqlMapExecutorTestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected final void testAndVerifyQueryForObject(SqlMapExecutor executor) throws Exception {
    final String queryForObjectId = "queryForObjectId";
    executor.queryForObject(queryForObjectId);
    executor.queryForObject(queryForObjectId, new Object());
    executor.queryForObject(queryForObjectId, new Object(), new Object());

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    Method queryForObject1 = executor.getClass().getDeclaredMethod("queryForObject", String.class);
    Method queryForObject2 = executor.getClass().getDeclaredMethod("queryForObject", String.class, Object.class);
    Method queryForObject3 = executor.getClass().getDeclaredMethod("queryForObject", String.class, Object.class,
            Object.class);
    verifier.verifyTrace(event("IBATIS", queryForObject1, Expectations.cachedArgs(queryForObjectId)));
    verifier.verifyTrace(event("IBATIS", queryForObject2, Expectations.cachedArgs(queryForObjectId)));
    verifier.verifyTrace(event("IBATIS", queryForObject3, Expectations.cachedArgs(queryForObjectId)));
}
 
Example 12
Source Project: pinpoint   Source File: SqlMapExecutorTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
protected final void testAndVerifyQueryForPaginatedList(SqlMapExecutor executor) throws Exception {
    final String queryForPaginatedListId = "queryForPaginatedListId";
    executor.queryForPaginatedList(queryForPaginatedListId, 1);
    executor.queryForPaginatedList(queryForPaginatedListId, new Object(), 1);

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    Method queryForPaginatedList1 = executor.getClass().getDeclaredMethod("queryForPaginatedList", String.class,
            int.class);
    Method queryForPaginatedList2 = executor.getClass().getDeclaredMethod("queryForPaginatedList", String.class,
            Object.class, int.class);
    verifier.verifyTrace(event("IBATIS", queryForPaginatedList1, Expectations.cachedArgs(queryForPaginatedListId)));
    verifier.verifyTrace(event("IBATIS", queryForPaginatedList2, Expectations.cachedArgs(queryForPaginatedListId)));
}
 
Example 13
Source Project: cobarclient   Source File: CobarSqlMapClientDaoSupport.java    License: Apache License 2.0 5 votes vote down vote up
public int batchInsert(final String statementName, final Collection<?> entities)
        throws DataAccessException {
    if (isPartitionBehaviorEnabled()) {
        int counter = 0;
        DataAccessException lastEx = null;
        for (Object parameterObject : entities) {
            try {
                getSqlMapClientTemplate().insert(statementName, parameterObject);
                counter++;
            } catch (DataAccessException e) {
                lastEx = e;
            }
        }
        if (lastEx != null) {
            throw lastEx;
        }
        return counter;
    } else {
        return (Integer) getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
            public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                executor.startBatch();
                for (Object item : entities) {
                    executor.insert(statementName, item);
                }
                return executor.executeBatch();
            }
        });
    }
}
 
Example 14
Source Project: cobarclient   Source File: CobarSqlMapClientDaoSupport.java    License: Apache License 2.0 5 votes vote down vote up
public int batchDelete(final String statementName, final Collection<?> entities)
        throws DataAccessException {
    if (isPartitionBehaviorEnabled()) {
        int counter = 0;
        DataAccessException lastEx = null;
        for (Object entity : entities) {
            try {
                counter += getSqlMapClientTemplate().delete(statementName, entity);
            } catch (DataAccessException e) {
                lastEx = e;
            }
        }
        if (lastEx != null) {
            throw lastEx;
        }
        return counter;
    } else {
        return (Integer) getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
            public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                executor.startBatch();
                for (Object parameterObject : entities) {
                    executor.delete(statementName, parameterObject);
                }
                return executor.executeBatch();
            }
        });
    }
}
 
Example 15
Source Project: cobarclient   Source File: CobarSqlMapClientTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int update(final String statementName, final Object parameterObject)
        throws DataAccessException {
    auditSqlIfNecessary(statementName, parameterObject);

    long startTimestamp = System.currentTimeMillis();
    try {
        if (isPartitioningBehaviorEnabled()) {
            SortedMap<String, DataSource> dsMap = lookupDataSourcesByRouter(statementName,
                    parameterObject);
            if (!MapUtils.isEmpty(dsMap)) {

                SqlMapClientCallback action = new SqlMapClientCallback() {
                    public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                        return executor.update(statementName, parameterObject);
                    }
                };

                List<Object> results = executeInConcurrency(action, dsMap);
                Integer rowAffacted = 0;

                for (Object item : results) {
                    rowAffacted += (Integer) item;
                }
                return rowAffacted;
            }
        } // end if for partitioning status checking
        return super.update(statementName, parameterObject);
    } finally {
        if (isProfileLongTimeRunningSql()) {
            long interval = System.currentTimeMillis() - startTimestamp;
            if (interval > getLongTimeRunningSqlIntervalThreshold()) {
                logger
                        .warn(
                                "SQL Statement [{}] with parameter object [{}] ran out of the normal time range, it consumed [{}] milliseconds.",
                                new Object[] { statementName, parameterObject, interval });
            }
        }
    }
}
 
Example 16
Source Project: cobarclient   Source File: CobarSqlMapClientTemplate.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public int delete(final String statementName, final Object parameterObject)
        throws DataAccessException {
    auditSqlIfNecessary(statementName, parameterObject);

    long startTimestamp = System.currentTimeMillis();
    try {
        if (isPartitioningBehaviorEnabled()) {
            SortedMap<String, DataSource> dsMap = lookupDataSourcesByRouter(statementName,
                    parameterObject);
            if (!MapUtils.isEmpty(dsMap)) {

                SqlMapClientCallback action = new SqlMapClientCallback() {
                    public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                        return executor.delete(statementName, parameterObject);
                    }
                };

                if (dsMap.size() == 1) {
                    DataSource dataSource = dsMap.get(dsMap.firstKey());
                    return (Integer) executeWith(dataSource, action);
                } else {
                    List<Object> results = executeInConcurrency(action, dsMap);
                    Integer rowAffacted = 0;
                    for (Object item : results) {
                        rowAffacted += (Integer) item;
                    }
                    return rowAffacted;
                }
            }
        } // end if for partitioning status checking
        return super.delete(statementName, parameterObject);
    } finally {
        if (isProfileLongTimeRunningSql()) {
            long interval = System.currentTimeMillis() - startTimestamp;
            if (interval > getLongTimeRunningSqlIntervalThreshold()) {
                logger
                        .warn(
                                "SQL Statement [{}] with parameter object [{}] ran out of the normal time range, it consumed [{}] milliseconds.",
                                new Object[] { statementName, parameterObject, interval });
            }
        }
    }
}
 
Example 17
Source Project: cobarclient   Source File: CobarSqlMapClientTemplate.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * We support insert in 3 ways here:<br>
 * 
 * <pre>
 *      1- if no partitioning requirement is found:
 *          the insert will be delegated to the default insert behavior of {@link SqlMapClientTemplate};
 *      2- if partitioning support is enabled and 'parameterObject' is NOT a type of collection:
 *          we will search for routing rules against it and execute insertion as per the rule if found, 
 *          if no rule is found, the default data source will be used.
 *      3- if partitioning support is enabled and 'parameterObject' is a type of {@link BatchInsertTask}:
 *           this is a specific solution, mainly aimed for "insert into ..values(), (), ()" style insertion.
 *           In this situation, we will regroup the entities in the original collection into several sub-collections as per routing rules, 
 *           and submit the regrouped sub-collections to their corresponding target data sources.
 *           One thing to NOTE: in this situation, although we return a object as the result of insert, but it doesn't mean any thing to you, 
 *           because, "insert into ..values(), (), ()" style SQL doesn't return you a sensible primary key in this way. 
 *           this, function is optional, although we return a list of sub-insert result, but don't guarantee precise semantics.
 * </pre>
 * 
 * we can't just decide the execution branch on the Collection<?> type of
 * the 'parameterObject', because sometimes, maybe the application does want
 * to do insertion as per the parameterObject of its own.<br>
 */
@Override
public Object insert(final String statementName, final Object parameterObject)
        throws DataAccessException {
    auditSqlIfNecessary(statementName, parameterObject);
    long startTimestamp = System.currentTimeMillis();
    try {
        if (isPartitioningBehaviorEnabled()) {
            /**
             * sometimes, client will submit batch insert request like
             * "insert into ..values(), (), ()...", it's a rare situation,
             * but does exist, so we will create new executor on this kind
             * of request processing, and map each values to their target
             * data source and then reduce to sub-collection, finally,
             * submit each sub-collection of entities to executor to
             * execute.
             */
            if (parameterObject != null && parameterObject instanceof BatchInsertTask) {
                // map collection into mapping of data source and sub collection of entities
                logger.info(
                        "start to prepare batch insert operation with parameter type of:{}.",
                        parameterObject.getClass());

                return batchInsertAfterReordering(statementName, parameterObject);

            } else {
                DataSource targetDataSource = null;
                SqlMapClientCallback action = new SqlMapClientCallback() {
                    public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                        return executor.insert(statementName, parameterObject);
                    }
                };
                SortedMap<String, DataSource> resultDataSources = lookupDataSourcesByRouter(
                        statementName, parameterObject);
                if (MapUtils.isEmpty(resultDataSources) || resultDataSources.size() == 1) {
                    targetDataSource = getSqlMapClient().getDataSource(); // fall back to default data source.
                    if (resultDataSources.size() == 1) {
                        targetDataSource = resultDataSources.values().iterator().next();
                    }
                    return executeWith(targetDataSource, action);
                } else {
                    return executeInConcurrency(action, resultDataSources);
                }
            }

        } // end if for partitioning status checking
        return super.insert(statementName, parameterObject);
    } finally {
        if (isProfileLongTimeRunningSql()) {
            long interval = System.currentTimeMillis() - startTimestamp;
            if (interval > getLongTimeRunningSqlIntervalThreshold()) {
                logger
                        .warn(
                                "SQL Statement [{}] with parameter object [{}] ran out of the normal time range, it consumed [{}] milliseconds.",
                                new Object[] { statementName, parameterObject, interval });
            }
        }
    }
}