org.springframework.orm.ibatis.SqlMapClientCallback Java Examples
The following examples show how to use
org.springframework.orm.ibatis.SqlMapClientCallback.
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 File: CobarSqlMapClientTemplateWithNamespaceRouterTest.java From cobarclient with Apache License 2.0 | 6 votes |
/** * 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 #2
Source File: BaseIbatisDaoContext.java From AsuraFramework with Apache License 2.0 | 6 votes |
/** * * 批量删除指定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 #3
Source File: BaseIbatisDaoContext.java From AsuraFramework with Apache License 2.0 | 6 votes |
/** * * 批量更新指定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 #4
Source File: BaseIbatisDAO.java From AsuraFramework with Apache License 2.0 | 6 votes |
/** * * 批量删除指定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 #5
Source File: BaseIbatisDAO.java From AsuraFramework with Apache License 2.0 | 6 votes |
/** * * 批量更新指定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 #6
Source File: DefaultConcurrentRequestProcessor.java From cobarclient with Apache License 2.0 | 6 votes |
protected Object executeWith(Connection connection, SqlMapClientCallback action) { SqlMapSession session = getSqlMapClient().openSession(); try { try { session.setUserConnection(connection); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", e); } try { return action.doInSqlMapClient(session); } catch (SQLException ex) { throw new SQLErrorCodeSQLExceptionTranslator().translate("SqlMapClient operation", null, ex); } } finally { session.close(); } }
Example #7
Source File: IbatisDaoImpl.java From EserKnife with Apache License 2.0 | 5 votes |
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 #8
Source File: CobarSqlMapClientTemplate.java From cobarclient with Apache License 2.0 | 5 votes |
public List<Object> executeInConcurrency(SqlMapClientCallback action, SortedMap<String, DataSource> dsMap) { List<ConcurrentRequest> requests = new ArrayList<ConcurrentRequest>(); for (Map.Entry<String, DataSource> entry : dsMap.entrySet()) { ConcurrentRequest request = new ConcurrentRequest(); request.setAction(action); request.setDataSource(entry.getValue()); request.setExecutor(getDataSourceSpecificExecutors().get(entry.getKey())); requests.add(request); } List<Object> results = getConcurrentRequestProcessor().process(requests); return results; }
Example #9
Source File: CobarSqlMapClientTemplate.java From cobarclient with Apache License 2.0 | 5 votes |
@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 #10
Source File: CobarSqlMapClientDaoSupport.java From cobarclient with Apache License 2.0 | 5 votes |
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 #11
Source File: CobarSqlMapClientDaoSupport.java From cobarclient with Apache License 2.0 | 5 votes |
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 #12
Source File: IbatisDaoImpl.java From EserKnife with Apache License 2.0 | 5 votes |
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 #13
Source File: IbatisDaoImpl.java From EserKnife with Apache License 2.0 | 5 votes |
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 #14
Source File: ConcurrentRequest.java From cobarclient with Apache License 2.0 | 4 votes |
public SqlMapClientCallback getAction() { return action; }
Example #15
Source File: ConcurrentRequest.java From cobarclient with Apache License 2.0 | 4 votes |
public void setAction(SqlMapClientCallback action) { this.action = action; }
Example #16
Source File: DefaultConcurrentRequestProcessor.java From cobarclient with Apache License 2.0 | 4 votes |
public List<Object> process(List<ConcurrentRequest> requests) { List<Object> resultList = new ArrayList<Object>(); if (CollectionUtils.isEmpty(requests)) return resultList; List<RequestDepository> requestsDepo = fetchConnectionsAndDepositForLaterUse(requests); final CountDownLatch latch = new CountDownLatch(requestsDepo.size()); List<Future<Object>> futures = new ArrayList<Future<Object>>(); try { for (RequestDepository rdepo : requestsDepo) { ConcurrentRequest request = rdepo.getOriginalRequest(); final SqlMapClientCallback action = request.getAction(); final Connection connection = rdepo.getConnectionToUse(); futures.add(request.getExecutor().submit(new Callable<Object>() { public Object call() throws Exception { try { return executeWith(connection, action); } finally { latch.countDown(); } } })); } try { latch.await(); } catch (InterruptedException e) { throw new ConcurrencyFailureException( "interrupted when processing data access request in concurrency", e); } } finally { for (RequestDepository depo : requestsDepo) { Connection springCon = depo.getConnectionToUse(); DataSource dataSource = depo.getOriginalRequest().getDataSource(); try { if (springCon != null) { if (depo.isTransactionAware()) { springCon.close(); } else { DataSourceUtils.doReleaseConnection(springCon, dataSource); } } } catch (Throwable ex) { logger.info("Could not close JDBC Connection", ex); } } } fillResultListWithFutureResults(futures, resultList); return resultList; }
Example #17
Source File: CobarSqlMapClientTemplate.java From cobarclient with Apache License 2.0 | 4 votes |
@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 #18
Source File: CobarSqlMapClientTemplate.java From cobarclient with Apache License 2.0 | 4 votes |
/** * 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 }); } } } }
Example #19
Source File: CobarSqlMapClientTemplate.java From cobarclient with Apache License 2.0 | 2 votes |
/** * NOTE: don't use this method for distributed data access.<br> * If you are sure that the data access operations will be distributed in a * database cluster in the future or even it happens just now, don't use * this method, because we can't get enough context information to route * these data access operations correctly. */ @Override public Object execute(SqlMapClientCallback action) throws DataAccessException { return super.execute(action); }
Example #20
Source File: CobarSqlMapClientTemplate.java From cobarclient with Apache License 2.0 | 2 votes |
/** * NOTE: don't use this method for distributed data access.<br> * If you are sure that the data access operations will be distributed in a * database cluster in the future or even it happens just now, don't use * this method, because we can't get enough context information to route * these data access operations correctly. */ @SuppressWarnings("unchecked") @Override public List executeWithListResult(SqlMapClientCallback action) throws DataAccessException { return super.executeWithListResult(action); }
Example #21
Source File: CobarSqlMapClientTemplate.java From cobarclient with Apache License 2.0 | 2 votes |
/** * NOTE: don't use this method for distributed data access.<br> * If you are sure that the data access operations will be distributed in a * database cluster in the future or even it happens just now, don't use * this method, because we can't get enough context information to route * these data access operations correctly. */ @SuppressWarnings("unchecked") @Override public Map executeWithMapResult(SqlMapClientCallback action) throws DataAccessException { return super.executeWithMapResult(action); }