iBatis分页

本文介绍了一种在不修改源码和不依赖Spring配置的情况下,实现iBatis物理分页功能的方法。通过创建与现有类同名的类并替换原有的executeQuery方法,实现了条件分页查询,并确保了类加载顺序的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习iBatis的分页功能,iBatis默认的分页是采用游标滚动的方式来实现的,这种方式在大数据量的情况下便会OOM了,因此一般都采用手写分页SQL语句使用数据库物理分页方式实现,参考了网上很多网友所写的如何实现像hibernate一样使用方言的方式来实现分页功能,基本上千篇一律都是继承com.ibatis.sqlmap.engine.execution.SqlExecutor类然后在spring中进行注入等等,操作复杂编码甚多,方法不可取。

另外还有些是修改iBatis的jar包来实现,本人觉得这种方法更不可取。
基于网友们的思想,自己实现了另一种方法,不用修改源码,不用在spring中做任何配置即可实现物理分页功能:
条件
1、JVM类的加载是通过Class.forName(String cls)来实现,根据这个原理可以自己写一个与com.ibatis.sqlmap.engine.execution.SqlExecutor同名类;
2、java web类的加载顺序是:首先是web容器的相关类与jar包,然后是web工程下面WEB-INF/classes/下的所有类,最后才是WEB-INF/lib下的所有jar包;
有了以上的先决条件就好办了,可以在你的项目src目录下建包com.ibatis.sqlmap.engine.execution,然后在此包下建类SqlExecutor,然后把iBatis包下的这个类的源码复制进来后做小小改动,原来的executeQuery方法改成私有、换名,换成什么名称随便,然后新建一个公有的executeQuery方法,分页功能就在这个方法体内实现;
这样一来,web容器首会找到WEB-INF/classes下的com.ibatis.sqlmap.engine.execution.SqlExecutor这个类,因而会忽略掉在ibatis包中的这个类,即实现了自定义的分页功能,又不用去破坏ibatis的包;
还有一点,也可以将自定义的这个类打成jar包放到lib中去,不过这时就要注意了,jar包的名称一定要在ibatis包的名称之前,也就是说ibatis-2.3.4.726.jar,那么这个jar就可以写成ibatis-2.3.4.725.jar,或者字母在ibatis这几个字母之前,这样才能正确加载自己写的那个类。
贴上代码:
SqlExecutor.java
Java代码收藏代码
  1. /*
  2. *Copyright2004ClintonBegin
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. packagecom.ibatis.sqlmap.engine.execution;
  17. importjava.sql.BatchUpdateException;
  18. importjava.sql.CallableStatement;
  19. importjava.sql.Connection;
  20. importjava.sql.PreparedStatement;
  21. importjava.sql.ResultSet;
  22. importjava.sql.SQLException;
  23. importjava.sql.Statement;
  24. importjava.sql.Types;
  25. importjava.util.ArrayList;
  26. importjava.util.List;
  27. importorg.apache.commons.logging.Log;
  28. importorg.apache.commons.logging.LogFactory;
  29. importcom.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
  30. importcom.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate;
  31. importcom.ibatis.sqlmap.engine.mapping.parameter.ParameterMap;
  32. importcom.ibatis.sqlmap.engine.mapping.parameter.ParameterMapping;
  33. importcom.ibatis.sqlmap.engine.mapping.result.ResultMap;
  34. importcom.ibatis.sqlmap.engine.mapping.result.ResultObjectFactoryUtil;
  35. importcom.ibatis.sqlmap.engine.mapping.statement.DefaultRowHandler;
  36. importcom.ibatis.sqlmap.engine.mapping.statement.MappedStatement;
  37. importcom.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback;
  38. importcom.ibatis.sqlmap.engine.scope.ErrorContext;
  39. importcom.ibatis.sqlmap.engine.scope.SessionScope;
  40. importcom.ibatis.sqlmap.engine.scope.StatementScope;
  41. /**
  42. *ClassresponsibleforexecutingtheSQL
  43. */
  44. @SuppressWarnings("unchecked")
  45. publicclassSqlExecutor{
  46. privatestaticfinalLoglog=LogFactory.getLog(SqlExecutor.class);
  47. //
  48. //Constants
  49. //
  50. /**
  51. *Constanttoletusknownottoskipanything
  52. */
  53. publicstaticfinalintNO_SKIPPED_RESULTS=0;
  54. /**
  55. *Constanttoletusknowtoincludeallrecords
  56. */
  57. publicstaticfinalintNO_MAXIMUM_RESULTS=-999999;
  58. publicSqlExecutor(){
  59. log.info("Customclass'SqlExecutor'Initialization");
  60. }
  61. //
  62. //PublicMethods
  63. //
  64. /**
  65. *Executeanupdate
  66. *
  67. *@paramstatementScope
  68. *-therequestscope
  69. *@paramconn
  70. *-thedatabaseconnection
  71. *@paramsql
  72. *-thesqlstatementtoexecute
  73. *@paramparameters
  74. *-theparametersforthesqlstatement
  75. *@return-thenumberofrecordschanged
  76. *@throwsSQLException
  77. *-iftheupdatefails
  78. */
  79. publicintexecuteUpdate(StatementScopestatementScope,Connectionconn,
  80. Stringsql,Object[]parameters)throwsSQLException{
  81. ErrorContexterrorContext=statementScope.getErrorContext();
  82. errorContext.setActivity("executingupdate");
  83. errorContext.setObjectId(sql);
  84. PreparedStatementps=null;
  85. setupResultObjectFactory(statementScope);
  86. introws=0;
  87. try{
  88. errorContext
  89. .setMoreInfo("ChecktheSQLStatement(preparationfailed).");
  90. ps=prepareStatement(statementScope.getSession(),conn,sql);
  91. setStatementTimeout(statementScope.getStatement(),ps);
  92. errorContext
  93. .setMoreInfo("Checktheparameters(setparametersfailed).");
  94. statementScope.getParameterMap().setParameters(statementScope,ps,
  95. parameters);
  96. errorContext.setMoreInfo("Checkthestatement(updatefailed).");
  97. ps.execute();
  98. rows=ps.getUpdateCount();
  99. }finally{
  100. closeStatement(statementScope.getSession(),ps);
  101. }
  102. returnrows;
  103. }
  104. /**
  105. *Addsastatementtoabatch
  106. *
  107. *@paramstatementScope
  108. *-therequestscope
  109. *@paramconn
  110. *-thedatabaseconnection
  111. *@paramsql
  112. *-thesqlstatement
  113. *@paramparameters
  114. *-theparametersforthestatement
  115. *@throwsSQLException
  116. *-ifthestatementfails
  117. */
  118. publicvoidaddBatch(StatementScopestatementScope,Connectionconn,
  119. Stringsql,Object[]parameters)throwsSQLException{
  120. Batchbatch=(Batch)statementScope.getSession().getBatch();
  121. if(batch==null){
  122. batch=newBatch();
  123. statementScope.getSession().setBatch(batch);
  124. }
  125. batch.addBatch(statementScope,conn,sql,parameters);
  126. }
  127. /**
  128. *Executeabatchofstatements
  129. *
  130. *@paramsessionScope
  131. *-thesessionscope
  132. *@return-thenumberofrowsimpactedbythebatch
  133. *@throwsSQLException
  134. *-ifastatementfails
  135. */
  136. publicintexecuteBatch(SessionScopesessionScope)throwsSQLException{
  137. introws=0;
  138. Batchbatch=(Batch)sessionScope.getBatch();
  139. if(batch!=null){
  140. try{
  141. rows=batch.executeBatch();
  142. }finally{
  143. batch.cleanupBatch(sessionScope);
  144. }
  145. }
  146. returnrows;
  147. }
  148. /**
  149. *Executeabatchofstatements
  150. *
  151. *@paramsessionScope
  152. *-thesessionscope
  153. *@return-aListofBatchResultobjects(maybenullifnobatchhasbeen
  154. *initiated).TherewillbeoneBatchResultobjectinthelistfor
  155. *eachsub-batchexecuted
  156. *@throwsSQLException
  157. *ifadatabaseaccesserroroccurs,orthedrivedoesnot
  158. *supportbatchstatements
  159. *@throwsBatchException
  160. *ifthedriverthrowsBatchUpdateException
  161. */
  162. publicListexecuteBatchDetailed(SessionScopesessionScope)
  163. throwsSQLException,BatchException{
  164. Listanswer=null;
  165. Batchbatch=(Batch)sessionScope.getBatch();
  166. if(batch!=null){
  167. try{
  168. answer=batch.executeBatchDetailed();
  169. }finally{
  170. batch.cleanupBatch(sessionScope);
  171. }
  172. }
  173. returnanswer;
  174. }
  175. /**
  176. *Longformofthemethodtoexecuteaquery
  177. *
  178. *@paramstatementScope
  179. *-therequestscope
  180. *@paramconn
  181. *-thedatabaseconnection
  182. *@paramsql
  183. *-theSQLstatementtoexecute
  184. *@paramparameters
  185. *-theparametersforthestatement
  186. *@paramskipResults
  187. *-thenumberofresultstoskip
  188. *@parammaxResults
  189. *-themaximumnumberofresultstoreturn
  190. *@paramcallback
  191. *-therowhandlerforthequery
  192. *@throwsSQLException
  193. *-ifthequeryfails
  194. */
  195. //-------------------------------分页代码重写(start)------------------------------------//
  196. //重写executeQuery方法,首先判断是否分页查询,分页查询先将分页SQL语句构建,然后执行iBatis默认的查询
  197. publicvoidexecuteQuery(StatementScopestatementScope,Connectionconn,
  198. Stringsql,Object[]parameters,intskipResults,intmaxResults,
  199. RowHandlerCallbackcallback)throwsSQLException{
  200. //取数据库产品名称
  201. StringdbName=conn.getMetaData().getDatabaseProductName();
  202. intlen=sql.length();
  203. //判断是否分页
  204. if((skipResults!=NO_SKIPPED_RESULTS||maxResults!=NO_MAXIMUM_RESULTS)){
  205. //根据数据库产品名称取对应的分页SQL语句
  206. sql=Dialect.getLimitString(dbName,sql,skipResults,maxResults);
  207. //分页语句是否存在
  208. if(sql.length()!=len){
  209. skipResults=NO_SKIPPED_RESULTS;
  210. maxResults=NO_MAXIMUM_RESULTS;
  211. }
  212. }
  213. iBatisExecuteQuery(statementScope,conn,sql,parameters,skipResults,
  214. maxResults,callback);
  215. }
  216. //iBatis包中默认的executeQuery方法
  217. privatevoidiBatisExecuteQuery(StatementScopestatementScope,
  218. Connectionconn,Stringsql,Object[]parameters,intskipResults,
  219. intmaxResults,RowHandlerCallbackcallback)throwsSQLException{
  220. ErrorContexterrorContext=statementScope.getErrorContext();
  221. errorContext.setActivity("executingquery");
  222. errorContext.setObjectId(sql);
  223. PreparedStatementps=null;
  224. ResultSetrs=null;
  225. setupResultObjectFactory(statementScope);
  226. try{
  227. errorContext
  228. .setMoreInfo("ChecktheSQLStatement(preparationfailed).");
  229. IntegerrsType=statementScope.getStatement().getResultSetType();
  230. if(rsType!=null){
  231. ps=prepareStatement(statementScope.getSession(),conn,sql,
  232. rsType);
  233. }else{
  234. ps=prepareStatement(statementScope.getSession(),conn,sql);
  235. }
  236. setStatementTimeout(statementScope.getStatement(),ps);
  237. IntegerfetchSize=statementScope.getStatement().getFetchSize();
  238. if(fetchSize!=null){
  239. ps.setFetchSize(fetchSize.intValue());
  240. }
  241. errorContext
  242. .setMoreInfo("Checktheparameters(setparametersfailed).");
  243. statementScope.getParameterMap().setParameters(statementScope,ps,
  244. parameters);
  245. errorContext.setMoreInfo("Checkthestatement(queryfailed).");
  246. ps.execute();
  247. errorContext
  248. .setMoreInfo("Checktheresults(failedtoretrieveresults).");
  249. //BeginResultSetHandling
  250. rs=handleMultipleResults(ps,statementScope,skipResults,
  251. maxResults,callback);
  252. //EndResultSetHandling
  253. }finally{
  254. try{
  255. closeResultSet(rs);
  256. }finally{
  257. closeStatement(statementScope.getSession(),ps);
  258. }
  259. }
  260. }
  261. //--------------------分页代码重写(end)-------------------------------------//
  262. /**
  263. *Executeastoredprocedurethatupdatesdata
  264. *
  265. *@paramstatementScope
  266. *-therequestscope
  267. *@paramconn
  268. *-thedatabaseconnection
  269. *@paramsql
  270. *-theSQLtocalltheprocedure
  271. *@paramparameters
  272. *-theparametersfortheprocedure
  273. *@return-therowsimpactedbytheprocedure
  274. *@throwsSQLException
  275. *-iftheprocedurefails
  276. */
  277. publicintexecuteUpdateProcedure(StatementScopestatementScope,
  278. Connectionconn,Stringsql,Object[]parameters)
  279. throwsSQLException{
  280. ErrorContexterrorContext=statementScope.getErrorContext();
  281. errorContext.setActivity("executingupdateprocedure");
  282. errorContext.setObjectId(sql);
  283. CallableStatementcs=null;
  284. setupResultObjectFactory(statementScope);
  285. introws=0;
  286. try{
  287. errorContext
  288. .setMoreInfo("ChecktheSQLStatement(preparationfailed).");
  289. cs=prepareCall(statementScope.getSession(),conn,sql);
  290. setStatementTimeout(statementScope.getStatement(),cs);
  291. ParameterMapparameterMap=statementScope.getParameterMap();
  292. ParameterMapping[]mappings=parameterMap.getParameterMappings();
  293. errorContext
  294. .setMoreInfo("Checktheoutputparameters(registeroutputparametersfailed).");
  295. registerOutputParameters(cs,mappings);
  296. errorContext
  297. .setMoreInfo("Checktheparameters(setparametersfailed).");
  298. parameterMap.setParameters(statementScope,cs,parameters);
  299. errorContext
  300. .setMoreInfo("Checkthestatement(updateprocedurefailed).");
  301. cs.execute();
  302. rows=cs.getUpdateCount();
  303. errorContext
  304. .setMoreInfo("Checktheoutputparameters(retrievalofoutputparametersfailed).");
  305. retrieveOutputParameters(statementScope,cs,mappings,parameters,
  306. null);
  307. }finally{
  308. closeStatement(statementScope.getSession(),cs);
  309. }
  310. returnrows;
  311. }
  312. /**
  313. *Executeastoredprocedure
  314. *
  315. *@paramstatementScope
  316. *-therequestscope
  317. *@paramconn
  318. *-thedatabaseconnection
  319. *@paramsql
  320. *-thesqltocalltheprocedure
  321. *@paramparameters
  322. *-theparametersfortheprocedure
  323. *@paramskipResults
  324. *-thenumberofresultstoskip
  325. *@parammaxResults
  326. *-themaximumnumberofresultstoreturn
  327. *@paramcallback
  328. *-arowhandlerforprocessingtheresults
  329. *@throwsSQLException
  330. *-iftheprocedurefails
  331. */
  332. publicvoidexecuteQueryProcedure(StatementScopestatementScope,
  333. Connectionconn,Stringsql,Object[]parameters,intskipResults,
  334. intmaxResults,RowHandlerCallbackcallback)throwsSQLException{
  335. ErrorContexterrorContext=statementScope.getErrorContext();
  336. errorContext.setActivity("executingqueryprocedure");
  337. errorContext.setObjectId(sql);
  338. CallableStatementcs=null;
  339. ResultSetrs=null;
  340. setupResultObjectFactory(statementScope);
  341. try{
  342. errorContext
  343. .setMoreInfo("ChecktheSQLStatement(preparationfailed).");
  344. IntegerrsType=statementScope.getStatement().getResultSetType();
  345. if(rsType!=null){
  346. cs=prepareCall(statementScope.getSession(),conn,sql,rsType);
  347. }else{
  348. cs=prepareCall(statementScope.getSession(),conn,sql);
  349. }
  350. setStatementTimeout(statementScope.getStatement(),cs);
  351. IntegerfetchSize=statementScope.getStatement().getFetchSize();
  352. if(fetchSize!=null){
  353. cs.setFetchSize(fetchSize.intValue());
  354. }
  355. ParameterMapparameterMap=statementScope.getParameterMap();
  356. ParameterMapping[]mappings=parameterMap.getParameterMappings();
  357. errorContext
  358. .setMoreInfo("Checktheoutputparameters(registeroutputparametersfailed).");
  359. registerOutputParameters(cs,mappings);
  360. errorContext
  361. .setMoreInfo("Checktheparameters(setparametersfailed).");
  362. parameterMap.setParameters(statementScope,cs,parameters);
  363. errorContext
  364. .setMoreInfo("Checkthestatement(updateprocedurefailed).");
  365. cs.execute();
  366. errorContext
  367. .setMoreInfo("Checktheresults(failedtoretrieveresults).");
  368. //BeginResultSetHandling
  369. rs=handleMultipleResults(cs,statementScope,skipResults,
  370. maxResults,callback);
  371. //EndResultSetHandling
  372. errorContext
  373. .setMoreInfo("Checktheoutputparameters(retrievalofoutputparametersfailed).");
  374. retrieveOutputParameters(statementScope,cs,mappings,parameters,
  375. callback);
  376. }finally{
  377. try{
  378. closeResultSet(rs);
  379. }finally{
  380. closeStatement(statementScope.getSession(),cs);
  381. }
  382. }
  383. }
  384. privateResultSethandleMultipleResults(PreparedStatementps,
  385. StatementScopestatementScope,intskipResults,intmaxResults,
  386. RowHandlerCallbackcallback)throwsSQLException{
  387. ResultSetrs;
  388. rs=getFirstResultSet(statementScope,ps);
  389. if(rs!=null){
  390. handleResults(statementScope,rs,skipResults,maxResults,callback);
  391. }
  392. //MultipleResultSethandling
  393. if(callback.getRowHandler()instanceofDefaultRowHandler){
  394. MappedStatementstatement=statementScope.getStatement();
  395. DefaultRowHandlerdefaultRowHandler=((DefaultRowHandler)callback
  396. .getRowHandler());
  397. if(statement.hasMultipleResultMaps()){
  398. ListmultipleResults=newArrayList();
  399. multipleResults.add(defaultRowHandler.getList());
  400. ResultMap[]resultMaps=statement.getAdditionalResultMaps();
  401. inti=0;
  402. while(moveToNextResultsSafely(statementScope,ps)){
  403. if(i>=resultMaps.length)
  404. break;
  405. ResultMaprm=resultMaps[i];
  406. statementScope.setResultMap(rm);
  407. rs=ps.getResultSet();
  408. DefaultRowHandlerrh=newDefaultRowHandler();
  409. handleResults(statementScope,rs,skipResults,maxResults,
  410. newRowHandlerCallback(rm,null,rh));
  411. multipleResults.add(rh.getList());
  412. i++;
  413. }
  414. defaultRowHandler.setList(multipleResults);
  415. statementScope.setResultMap(statement.getResultMap());
  416. }else{
  417. while(moveToNextResultsSafely(statementScope,ps))
  418. ;
  419. }
  420. }
  421. //EndadditionalResultSethandling
  422. returnrs;
  423. }
  424. privateResultSetgetFirstResultSet(StatementScopescope,Statementstmt)
  425. throwsSQLException{
  426. ResultSetrs=null;
  427. booleanhasMoreResults=true;
  428. while(hasMoreResults){
  429. rs=stmt.getResultSet();
  430. if(rs!=null){
  431. break;
  432. }
  433. hasMoreResults=moveToNextResultsIfPresent(scope,stmt);
  434. }
  435. returnrs;
  436. }
  437. privatebooleanmoveToNextResultsIfPresent(StatementScopescope,
  438. Statementstmt)throwsSQLException{
  439. booleanmoreResults;
  440. //ThisisthemessedupJDBCapproachfordeterminingiftherearemore
  441. //results
  442. moreResults=!(((moveToNextResultsSafely(scope,stmt)==false)&&(stmt
  443. .getUpdateCount()==-1)));
  444. returnmoreResults;
  445. }
  446. privatebooleanmoveToNextResultsSafely(StatementScopescope,Statementstmt)
  447. throwsSQLException{
  448. if(forceMultipleResultSetSupport(scope)
  449. ||stmt.getConnection().getMetaData()
  450. .supportsMultipleResultSets()){
  451. returnstmt.getMoreResults();
  452. }
  453. returnfalse;
  454. }
  455. privatebooleanforceMultipleResultSetSupport(StatementScopescope){
  456. return((SqlMapClientImpl)scope.getSession().getSqlMapClient())
  457. .getDelegate().isForceMultipleResultSetSupport();
  458. }
  459. privatevoidhandleResults(StatementScopestatementScope,ResultSetrs,
  460. intskipResults,intmaxResults,RowHandlerCallbackcallback)
  461. throwsSQLException{
  462. try{
  463. statementScope.setResultSet(rs);
  464. ResultMapresultMap=statementScope.getResultMap();
  465. if(resultMap!=null){
  466. //SkipResults
  467. if(rs.getType()!=ResultSet.TYPE_FORWARD_ONLY){
  468. if(skipResults>0){
  469. rs.absolute(skipResults);
  470. }
  471. }else{
  472. for(inti=0;i<skipResults;i++){
  473. if(!rs.next()){
  474. return;
  475. }
  476. }
  477. }
  478. //GetResults
  479. intresultsFetched=0;
  480. while((maxResults==SqlExecutor.NO_MAXIMUM_RESULTS||resultsFetched<maxResults)
  481. &&rs.next()){
  482. Object[]columnValues=resultMap.resolveSubMap(
  483. statementScope,rs).getResults(statementScope,rs);
  484. callback.handleResultObject(statementScope,columnValues,
  485. rs);
  486. resultsFetched++;
  487. }
  488. }
  489. }finally{
  490. statementScope.setResultSet(null);
  491. }
  492. }
  493. privatevoidretrieveOutputParameters(StatementScopestatementScope,
  494. CallableStatementcs,ParameterMapping[]mappings,
  495. Object[]parameters,RowHandlerCallbackcallback)
  496. throwsSQLException{
  497. for(inti=0;i<mappings.length;i++){
  498. ParameterMappingmapping=((ParameterMapping)mappings[i]);
  499. if(mapping.isOutputAllowed()){
  500. if("java.sql.ResultSet".equalsIgnoreCase(mapping
  501. .getJavaTypeName())){
  502. ResultSetrs=(ResultSet)cs.getObject(i+1);
  503. ResultMapresultMap;
  504. if(mapping.getResultMapName()==null){
  505. resultMap=statementScope.getResultMap();
  506. handleOutputParameterResults(statementScope,resultMap,
  507. rs,callback);
  508. }else{
  509. SqlMapClientImplclient=(SqlMapClientImpl)statementScope
  510. .getSession().getSqlMapClient();
  511. resultMap=client.getDelegate().getResultMap(
  512. mapping.getResultMapName());
  513. DefaultRowHandlerrowHandler=newDefaultRowHandler();
  514. RowHandlerCallbackhandlerCallback=newRowHandlerCallback(
  515. resultMap,null,rowHandler);
  516. handleOutputParameterResults(statementScope,resultMap,
  517. rs,handlerCallback);
  518. parameters[i]=rowHandler.getList();
  519. }
  520. rs.close();
  521. }else{
  522. parameters[i]=mapping.getTypeHandler().getResult(cs,
  523. i+1);
  524. }
  525. }
  526. }
  527. }
  528. privatevoidregisterOutputParameters(CallableStatementcs,
  529. ParameterMapping[]mappings)throwsSQLException{
  530. for(inti=0;i<mappings.length;i++){
  531. ParameterMappingmapping=((ParameterMapping)mappings[i]);
  532. if(mapping.isOutputAllowed()){
  533. if(null!=mapping.getTypeName()
  534. &&!mapping.getTypeName().equals("")){//@added
  535. cs.registerOutParameter(i+1,mapping.getJdbcType(),
  536. mapping.getTypeName());
  537. }else{
  538. if(mapping.getNumericScale()!=null
  539. &&(mapping.getJdbcType()==Types.NUMERIC||mapping
  540. .getJdbcType()==Types.DECIMAL)){
  541. cs.registerOutParameter(i+1,mapping.getJdbcType(),
  542. mapping.getNumericScale().intValue());
  543. }else{
  544. cs.registerOutParameter(i+1,mapping.getJdbcType());
  545. }
  546. }
  547. }
  548. }
  549. }
  550. privatevoidhandleOutputParameterResults(StatementScopestatementScope,
  551. ResultMapresultMap,ResultSetrs,RowHandlerCallbackcallback)
  552. throwsSQLException{
  553. ResultMaporig=statementScope.getResultMap();
  554. try{
  555. statementScope.setResultSet(rs);
  556. if(resultMap!=null){
  557. statementScope.setResultMap(resultMap);
  558. //GetResults
  559. while(rs.next()){
  560. Object[]columnValues=resultMap.resolveSubMap(
  561. statementScope,rs).getResults(statementScope,rs);
  562. callback.handleResultObject(statementScope,columnValues,
  563. rs);
  564. }
  565. }
  566. }finally{
  567. statementScope.setResultSet(null);
  568. statementScope.setResultMap(orig);
  569. }
  570. }
  571. /**
  572. *Cleanupanybatchesonthesession
  573. *
  574. *@paramsessionScope
  575. *-thesessiontocleanup
  576. */
  577. publicvoidcleanup(SessionScopesessionScope){
  578. Batchbatch=(Batch)sessionScope.getBatch();
  579. if(batch!=null){
  580. batch.cleanupBatch(sessionScope);
  581. sessionScope.setBatch(null);
  582. }
  583. }
  584. privatePreparedStatementprepareStatement(SessionScopesessionScope,
  585. Connectionconn,Stringsql,IntegerrsType)throwsSQLException{
  586. SqlMapExecutorDelegatedelegate=((SqlMapClientImpl)sessionScope
  587. .getSqlMapExecutor()).getDelegate();
  588. if(sessionScope.hasPreparedStatementFor(sql)){
  589. returnsessionScope.getPreparedStatement((sql));
  590. }else{
  591. PreparedStatementps=conn.prepareStatement(sql,
  592. rsType.intValue(),ResultSet.CONCUR_READ_ONLY);
  593. sessionScope.putPreparedStatement(delegate,sql,ps);
  594. returnps;
  595. }
  596. }
  597. privateCallableStatementprepareCall(SessionScopesessionScope,
  598. Connectionconn,Stringsql,IntegerrsType)throwsSQLException{
  599. SqlMapExecutorDelegatedelegate=((SqlMapClientImpl)sessionScope
  600. .getSqlMapExecutor()).getDelegate();
  601. if(sessionScope.hasPreparedStatementFor(sql)){
  602. return(CallableStatement)sessionScope.getPreparedStatement((sql));
  603. }else{
  604. CallableStatementcs=conn.prepareCall(sql,rsType.intValue(),
  605. ResultSet.CONCUR_READ_ONLY);
  606. sessionScope.putPreparedStatement(delegate,sql,cs);
  607. returncs;
  608. }
  609. }
  610. privatestaticPreparedStatementprepareStatement(
  611. SessionScopesessionScope,Connectionconn,Stringsql)
  612. throwsSQLException{
  613. SqlMapExecutorDelegatedelegate=((SqlMapClientImpl)sessionScope
  614. .getSqlMapExecutor()).getDelegate();
  615. if(sessionScope.hasPreparedStatementFor(sql)){
  616. returnsessionScope.getPreparedStatement((sql));
  617. }else{
  618. PreparedStatementps=conn.prepareStatement(sql);
  619. sessionScope.putPreparedStatement(delegate,sql,ps);
  620. returnps;
  621. }
  622. }
  623. privateCallableStatementprepareCall(SessionScopesessionScope,
  624. Connectionconn,Stringsql)throwsSQLException{
  625. SqlMapExecutorDelegatedelegate=((SqlMapClientImpl)sessionScope
  626. .getSqlMapExecutor()).getDelegate();
  627. if(sessionScope.hasPreparedStatementFor(sql)){
  628. return(CallableStatement)sessionScope.getPreparedStatement((sql));
  629. }else{
  630. CallableStatementcs=conn.prepareCall(sql);
  631. sessionScope.putPreparedStatement(delegate,sql,cs);
  632. returncs;
  633. }
  634. }
  635. privatestaticvoidcloseStatement(SessionScopesessionScope,
  636. PreparedStatementps){
  637. if(ps!=null){
  638. if(!sessionScope.hasPreparedStatement(ps)){
  639. try{
  640. ps.close();
  641. }catch(SQLExceptione){
  642. //ignore
  643. }
  644. }
  645. }
  646. }
  647. /**
  648. *@paramrs
  649. */
  650. privatestaticvoidcloseResultSet(ResultSetrs){
  651. if(rs!=null){
  652. try{
  653. rs.close();
  654. }catch(SQLExceptione){
  655. //ignore
  656. }
  657. }
  658. }
  659. privatestaticvoidsetStatementTimeout(MappedStatementmappedStatement,
  660. Statementstatement)throwsSQLException{
  661. if(mappedStatement.getTimeout()!=null){
  662. statement.setQueryTimeout(mappedStatement.getTimeout().intValue());
  663. }
  664. }
  665. //
  666. //InnerClasses
  667. //
  668. privatestaticclassBatch{
  669. privateStringcurrentSql;
  670. privateListstatementList=newArrayList();
  671. privateListbatchResultList=newArrayList();
  672. privateintsize;
  673. /**
  674. *Createanewbatch
  675. */
  676. publicBatch(){
  677. this.size=0;
  678. }
  679. /**
  680. *Getterforthebatchsize
  681. *
  682. *@return-thebatchsize
  683. */
  684. publicintgetSize(){
  685. returnsize;
  686. }
  687. /**
  688. *Addapreparedstatementtothebatch
  689. *
  690. *@paramstatementScope
  691. *-therequestscope
  692. *@paramconn
  693. *-thedatabaseconnection
  694. *@paramsql
  695. *-theSQLtoadd
  696. *@paramparameters
  697. *-theparametersfortheSQL
  698. *@throwsSQLException
  699. *-ifthepreparefortheSQLfails
  700. */
  701. publicvoidaddBatch(StatementScopestatementScope,Connectionconn,
  702. Stringsql,Object[]parameters)throwsSQLException{
  703. PreparedStatementps=null;
  704. if(currentSql!=null&&currentSql.equals(sql)){
  705. intlast=statementList.size()-1;
  706. ps=(PreparedStatement)statementList.get(last);
  707. }else{
  708. ps=prepareStatement(statementScope.getSession(),conn,sql);
  709. setStatementTimeout(statementScope.getStatement(),ps);
  710. currentSql=sql;
  711. statementList.add(ps);
  712. batchResultList.add(newBatchResult(statementScope
  713. .getStatement().getId(),sql));
  714. }
  715. statementScope.getParameterMap().setParameters(statementScope,ps,
  716. parameters);
  717. ps.addBatch();
  718. size++;
  719. }
  720. /**
  721. *TODO(JeffButler)-maybethismethodshouldbedeprecatedinsome
  722. *release,andthenremovedinsomeevenlaterrelease.
  723. *executeBatchDetailedgivesmuchmorecompleteinformation.<p/>
  724. *Executethecurrentsession'sbatch
  725. *
  726. *@return-thenumberofrowsupdated
  727. *@throwsSQLException
  728. *-ifthebatchfails
  729. */
  730. publicintexecuteBatch()throwsSQLException{
  731. inttotalRowCount=0;
  732. for(inti=0,n=statementList.size();i<n;i++){
  733. PreparedStatementps=(PreparedStatement)statementList.get(i);
  734. int[]rowCounts=ps.executeBatch();
  735. for(intj=0;j<rowCounts.length;j++){
  736. if(rowCounts[j]==Statement.SUCCESS_NO_INFO){
  737. //donothing
  738. }elseif(rowCounts[j]==Statement.EXECUTE_FAILED){
  739. thrownewSQLException(
  740. "Thebatchedstatementatindex"+j
  741. +"failedtoexecute.");
  742. }else{
  743. totalRowCount+=rowCounts[j];
  744. }
  745. }
  746. }
  747. returntotalRowCount;
  748. }
  749. /**
  750. *Batchexecutionmethodthatreturnsalltheinformationthedriver
  751. *hastooffer.
  752. *
  753. *@returnaListofBatchResultobjects
  754. *@throwsBatchException
  755. *(anSQLExceptionsubclass)ifanynestedbatchfails
  756. *@throwsSQLException
  757. *ifadatabaseaccesserroroccurs,orthedrivedoesnot
  758. *supportbatchstatements
  759. *@throwsBatchException
  760. *ifthedriverthrowsBatchUpdateException
  761. */
  762. publicListexecuteBatchDetailed()throwsSQLException,BatchException{
  763. Listanswer=newArrayList();
  764. for(inti=0,n=statementList.size();i<n;i++){
  765. BatchResultbr=(BatchResult)batchResultList.get(i);
  766. PreparedStatementps=(PreparedStatement)statementList.get(i);
  767. try{
  768. br.setUpdateCounts(ps.executeBatch());
  769. }catch(BatchUpdateExceptione){
  770. StringBuffermessage=newStringBuffer();
  771. message.append("Subbatchnumber");
  772. message.append(i+1);
  773. message.append("failed.");
  774. if(i>0){
  775. message.append("");
  776. message.append(i);
  777. message
  778. .append("priorsubbatch(s)completedsuccessfully,butwillberolledback.");
  779. }
  780. thrownewBatchException(message.toString(),e,answer,br
  781. .getStatementId(),br.getSql());
  782. }
  783. answer.add(br);
  784. }
  785. returnanswer;
  786. }
  787. /**
  788. *Closeallthestatementsinthebatchandclearallthestatements
  789. *
  790. *@paramsessionScope
  791. */
  792. publicvoidcleanupBatch(SessionScopesessionScope){
  793. for(inti=0,n=statementList.size();i<n;i++){
  794. PreparedStatementps=(PreparedStatement)statementList.get(i);
  795. closeStatement(sessionScope,ps);
  796. }
  797. currentSql=null;
  798. statementList.clear();
  799. batchResultList.clear();
  800. size=0;
  801. }
  802. }
  803. privatevoidsetupResultObjectFactory(StatementScopestatementScope){
  804. SqlMapClientImplclient=(SqlMapClientImpl)statementScope
  805. .getSession().getSqlMapClient();
  806. ResultObjectFactoryUtil.setResultObjectFactory(client
  807. .getResultObjectFactory());
  808. ResultObjectFactoryUtil.setStatementId(statementScope.getStatement()
  809. .getId());
  810. }
  811. }

Dialect.java
Java代码收藏代码
  1. packagecom.ibatis.sqlmap.engine.execution;
  2. publicclassDialect{
  3. privatestaticfinalStringSQL_END_DELIMITER=";";
  4. publicstaticStringgetLimitString(StringdbName,Stringsql,intoffset,
  5. intlimit){
  6. StringlimitString=sql;
  7. if(dbName.toLowerCase().indexOf("mysql")!=-1){
  8. limitString=getMysqlLimitString(sql,offset,limit);
  9. }
  10. if(dbName.toLowerCase().indexOf("microsoftsqlserver")!=-1){
  11. limitString=getMssqlLimitString(sql,offset,limit);
  12. }
  13. if(dbName.toLowerCase().indexOf("oracle")!=-1){
  14. limitString=getOracleLimitString(sql,offset,limit);
  15. }
  16. if(dbName.toLowerCase().indexOf("db2")!=-1){
  17. limitString=getDB2LimitString(sql,offset,limit);
  18. }
  19. returnlimitString;
  20. }
  21. privatestaticStringgetMysqlLimitString(Stringsql,intoffset,intlimit){
  22. sql=trim(sql);
  23. StringBuffersb=newStringBuffer(sql.length()+20);
  24. sb.append(sql);
  25. if(offset>0){
  26. sb.append("limit").append(offset).append(',').append(limit);
  27. }else{
  28. sb.append("limit").append(limit);
  29. }
  30. returnsb.toString();
  31. }
  32. privatestaticStringgetOracleLimitString(Stringsql,intoffset,intlimit){
  33. sql=trim(sql);
  34. StringBuffersb=newStringBuffer(sql.length()+100);
  35. if(offset>0){
  36. sb.append("select*from(selectrow_.*,rownumrownum_from(")
  37. .append(sql).append(")row_whererownum<=").append(
  38. offset+limit).append(")whererownum_>")
  39. .append(offset);
  40. }else{
  41. sb.append("select*from(").append(sql).append(
  42. ")whererownum<=").append(limit);
  43. }
  44. returnsb.toString();
  45. }
  46. privatestaticStringgetMssqlLimitString(Stringsql,intoffset,intlimit){
  47. returnnull;
  48. }
  49. privatestaticStringgetDB2LimitString(Stringsql,intoffset,intlimit){
  50. returnnull;
  51. }
  52. privatestaticStringtrim(Stringsql){
  53. sql=sql.trim();
  54. if(sql.endsWith(SQL_END_DELIMITER)){
  55. sql=sql.substring(0,sql.length()-1
  56. -SQL_END_DELIMITER.length());
  57. }
  58. returnsql;
  59. }
  60. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值