- 浏览: 44398 次
- 性别:
- 来自: 合肥市
文章分类
最新评论
iBatis分页
最近在学习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
Dialect.java
另外还有些是修改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
/* * Copyright 2004 Clinton Begin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibatis.sqlmap.engine.execution; import java.sql.BatchUpdateException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl; import com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate; import com.ibatis.sqlmap.engine.mapping.parameter.ParameterMap; import com.ibatis.sqlmap.engine.mapping.parameter.ParameterMapping; import com.ibatis.sqlmap.engine.mapping.result.ResultMap; import com.ibatis.sqlmap.engine.mapping.result.ResultObjectFactoryUtil; import com.ibatis.sqlmap.engine.mapping.statement.DefaultRowHandler; import com.ibatis.sqlmap.engine.mapping.statement.MappedStatement; import com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback; import com.ibatis.sqlmap.engine.scope.ErrorContext; import com.ibatis.sqlmap.engine.scope.SessionScope; import com.ibatis.sqlmap.engine.scope.StatementScope; /** * Class responsible for executing the SQL */ @SuppressWarnings ("unchecked") public class SqlExecutor { private static final Log log = LogFactory.getLog(SqlExecutor.class); // // Constants // /** * Constant to let us know not to skip anything */ public static final int NO_SKIPPED_RESULTS = 0; /** * Constant to let us know to include all records */ public static final int NO_MAXIMUM_RESULTS = -999999; public SqlExecutor() { log.info("Custom class 'SqlExecutor' Initialization"); } // // Public Methods // /** * Execute an update * * @param statementScope * - the request scope * @param conn * - the database connection * @param sql * - the sql statement to execute * @param parameters * - the parameters for the sql statement * @return - the number of records changed * @throws SQLException * - if the update fails */ public int executeUpdate(StatementScope statementScope, Connection conn, String sql, Object[] parameters) throws SQLException { ErrorContext errorContext = statementScope.getErrorContext(); errorContext.setActivity("executing update"); errorContext.setObjectId(sql); PreparedStatement ps = null; setupResultObjectFactory(statementScope); int rows = 0; try { errorContext .setMoreInfo("Check the SQL Statement (preparation failed)."); ps = prepareStatement(statementScope.getSession(), conn, sql); setStatementTimeout(statementScope.getStatement(), ps); errorContext .setMoreInfo("Check the parameters (set parameters failed)."); statementScope.getParameterMap().setParameters(statementScope, ps, parameters); errorContext.setMoreInfo("Check the statement (update failed)."); ps.execute(); rows = ps.getUpdateCount(); } finally { closeStatement(statementScope.getSession(), ps); } return rows; } /** * Adds a statement to a batch * * @param statementScope * - the request scope * @param conn * - the database connection * @param sql * - the sql statement * @param parameters * - the parameters for the statement * @throws SQLException * - if the statement fails */ public void addBatch(StatementScope statementScope, Connection conn, String sql, Object[] parameters) throws SQLException { Batch batch = (Batch) statementScope.getSession().getBatch(); if (batch == null) { batch = new Batch(); statementScope.getSession().setBatch(batch); } batch.addBatch(statementScope, conn, sql, parameters); } /** * Execute a batch of statements * * @param sessionScope * - the session scope * @return - the number of rows impacted by the batch * @throws SQLException * - if a statement fails */ public int executeBatch(SessionScope sessionScope) throws SQLException { int rows = 0; Batch batch = (Batch) sessionScope.getBatch(); if (batch != null) { try { rows = batch.executeBatch(); } finally { batch.cleanupBatch(sessionScope); } } return rows; } /** * Execute a batch of statements * * @param sessionScope * - the session scope * @return - a List of BatchResult objects (may be null if no batch has been * initiated). There will be one BatchResult object in the list for * each sub-batch executed * @throws SQLException * if a database access error occurs, or the drive does not * support batch statements * @throws BatchException * if the driver throws BatchUpdateException */ public List executeBatchDetailed(SessionScope sessionScope) throws SQLException, BatchException { List answer = null; Batch batch = (Batch) sessionScope.getBatch(); if (batch != null) { try { answer = batch.executeBatchDetailed(); } finally { batch.cleanupBatch(sessionScope); } } return answer; } /** * Long form of the method to execute a query * * @param statementScope * - the request scope * @param conn * - the database connection * @param sql * - the SQL statement to execute * @param parameters * - the parameters for the statement * @param skipResults * - the number of results to skip * @param maxResults * - the maximum number of results to return * @param callback * - the row handler for the query * @throws SQLException * - if the query fails */ //------------------------------- 分页代码重写(start) ------------------------------------// //重写executeQuery方法,首先判断是否分页查询,分页查询先将分页SQL语句构建,然后执行iBatis默认的查询 public void executeQuery(StatementScope statementScope, Connection conn, String sql, Object[] parameters, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException { //取数据库产品名称 String dbName = conn.getMetaData().getDatabaseProductName(); int len = sql.length(); //判断是否分页 if ((skipResults != NO_SKIPPED_RESULTS || maxResults != NO_MAXIMUM_RESULTS)) { //根据数据库产品名称取对应的分页SQL语句 sql = Dialect.getLimitString(dbName, sql, skipResults, maxResults); //分页语句是否存在 if (sql.length() != len) { skipResults = NO_SKIPPED_RESULTS; maxResults = NO_MAXIMUM_RESULTS; } } iBatisExecuteQuery(statementScope, conn, sql, parameters, skipResults, maxResults, callback); } //iBatis包中默认的executeQuery方法 private void iBatisExecuteQuery(StatementScope statementScope, Connection conn, String sql, Object[] parameters, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException { ErrorContext errorContext = statementScope.getErrorContext(); errorContext.setActivity("executing query"); errorContext.setObjectId(sql); PreparedStatement ps = null; ResultSet rs = null; setupResultObjectFactory(statementScope); try { errorContext .setMoreInfo("Check the SQL Statement (preparation failed)."); Integer rsType = statementScope.getStatement().getResultSetType(); if (rsType != null) { ps = prepareStatement(statementScope.getSession(), conn, sql, rsType); } else { ps = prepareStatement(statementScope.getSession(), conn, sql); } setStatementTimeout(statementScope.getStatement(), ps); Integer fetchSize = statementScope.getStatement().getFetchSize(); if (fetchSize != null) { ps.setFetchSize(fetchSize.intValue()); } errorContext .setMoreInfo("Check the parameters (set parameters failed)."); statementScope.getParameterMap().setParameters(statementScope, ps, parameters); errorContext.setMoreInfo("Check the statement (query failed)."); ps.execute(); errorContext .setMoreInfo("Check the results (failed to retrieve results)."); // Begin ResultSet Handling rs = handleMultipleResults(ps, statementScope, skipResults, maxResults, callback); // End ResultSet Handling } finally { try { closeResultSet(rs); } finally { closeStatement(statementScope.getSession(), ps); } } } //-------------------- 分页代码重写(end) -------------------------------------// /** * Execute a stored procedure that updates data * * @param statementScope * - the request scope * @param conn * - the database connection * @param sql * - the SQL to call the procedure * @param parameters * - the parameters for the procedure * @return - the rows impacted by the procedure * @throws SQLException * - if the procedure fails */ public int executeUpdateProcedure(StatementScope statementScope, Connection conn, String sql, Object[] parameters) throws SQLException { ErrorContext errorContext = statementScope.getErrorContext(); errorContext.setActivity("executing update procedure"); errorContext.setObjectId(sql); CallableStatement cs = null; setupResultObjectFactory(statementScope); int rows = 0; try { errorContext .setMoreInfo("Check the SQL Statement (preparation failed)."); cs = prepareCall(statementScope.getSession(), conn, sql); setStatementTimeout(statementScope.getStatement(), cs); ParameterMap parameterMap = statementScope.getParameterMap(); ParameterMapping[] mappings = parameterMap.getParameterMappings(); errorContext .setMoreInfo("Check the output parameters (register output parameters failed)."); registerOutputParameters(cs, mappings); errorContext .setMoreInfo("Check the parameters (set parameters failed)."); parameterMap.setParameters(statementScope, cs, parameters); errorContext .setMoreInfo("Check the statement (update procedure failed)."); cs.execute(); rows = cs.getUpdateCount(); errorContext .setMoreInfo("Check the output parameters (retrieval of output parameters failed)."); retrieveOutputParameters(statementScope, cs, mappings, parameters, null); } finally { closeStatement(statementScope.getSession(), cs); } return rows; } /** * Execute a stored procedure * * @param statementScope * - the request scope * @param conn * - the database connection * @param sql * - the sql to call the procedure * @param parameters * - the parameters for the procedure * @param skipResults * - the number of results to skip * @param maxResults * - the maximum number of results to return * @param callback * - a row handler for processing the results * @throws SQLException * - if the procedure fails */ public void executeQueryProcedure(StatementScope statementScope, Connection conn, String sql, Object[] parameters, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException { ErrorContext errorContext = statementScope.getErrorContext(); errorContext.setActivity("executing query procedure"); errorContext.setObjectId(sql); CallableStatement cs = null; ResultSet rs = null; setupResultObjectFactory(statementScope); try { errorContext .setMoreInfo("Check the SQL Statement (preparation failed)."); Integer rsType = statementScope.getStatement().getResultSetType(); if (rsType != null) { cs = prepareCall(statementScope.getSession(), conn, sql, rsType); } else { cs = prepareCall(statementScope.getSession(), conn, sql); } setStatementTimeout(statementScope.getStatement(), cs); Integer fetchSize = statementScope.getStatement().getFetchSize(); if (fetchSize != null) { cs.setFetchSize(fetchSize.intValue()); } ParameterMap parameterMap = statementScope.getParameterMap(); ParameterMapping[] mappings = parameterMap.getParameterMappings(); errorContext .setMoreInfo("Check the output parameters (register output parameters failed)."); registerOutputParameters(cs, mappings); errorContext .setMoreInfo("Check the parameters (set parameters failed)."); parameterMap.setParameters(statementScope, cs, parameters); errorContext .setMoreInfo("Check the statement (update procedure failed)."); cs.execute(); errorContext .setMoreInfo("Check the results (failed to retrieve results)."); // Begin ResultSet Handling rs = handleMultipleResults(cs, statementScope, skipResults, maxResults, callback); // End ResultSet Handling errorContext .setMoreInfo("Check the output parameters (retrieval of output parameters failed)."); retrieveOutputParameters(statementScope, cs, mappings, parameters, callback); } finally { try { closeResultSet(rs); } finally { closeStatement(statementScope.getSession(), cs); } } } private ResultSet handleMultipleResults(PreparedStatement ps, StatementScope statementScope, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException { ResultSet rs; rs = getFirstResultSet(statementScope, ps); if (rs != null) { handleResults(statementScope, rs, skipResults, maxResults, callback); } // Multiple ResultSet handling if (callback.getRowHandler() instanceof DefaultRowHandler) { MappedStatement statement = statementScope.getStatement(); DefaultRowHandler defaultRowHandler = ((DefaultRowHandler) callback .getRowHandler()); if (statement.hasMultipleResultMaps()) { List multipleResults = new ArrayList(); multipleResults.add(defaultRowHandler.getList()); ResultMap[] resultMaps = statement.getAdditionalResultMaps(); int i = 0; while (moveToNextResultsSafely(statementScope, ps)) { if (i >= resultMaps.length) break; ResultMap rm = resultMaps[i]; statementScope.setResultMap(rm); rs = ps.getResultSet(); DefaultRowHandler rh = new DefaultRowHandler(); handleResults(statementScope, rs, skipResults, maxResults, new RowHandlerCallback(rm, null, rh)); multipleResults.add(rh.getList()); i++; } defaultRowHandler.setList(multipleResults); statementScope.setResultMap(statement.getResultMap()); } else { while (moveToNextResultsSafely(statementScope, ps)) ; } } // End additional ResultSet handling return rs; } private ResultSet getFirstResultSet(StatementScope scope, Statement stmt) throws SQLException { ResultSet rs = null; boolean hasMoreResults = true; while (hasMoreResults) { rs = stmt.getResultSet(); if (rs != null) { break; } hasMoreResults = moveToNextResultsIfPresent(scope, stmt); } return rs; } private boolean moveToNextResultsIfPresent(StatementScope scope, Statement stmt) throws SQLException { boolean moreResults; // This is the messed up JDBC approach for determining if there are more // results moreResults = !(((moveToNextResultsSafely(scope, stmt) == false) && (stmt .getUpdateCount() == -1))); return moreResults; } private boolean moveToNextResultsSafely(StatementScope scope, Statement stmt) throws SQLException { if (forceMultipleResultSetSupport(scope) || stmt.getConnection().getMetaData() .supportsMultipleResultSets()) { return stmt.getMoreResults(); } return false; } private boolean forceMultipleResultSetSupport(StatementScope scope) { return ((SqlMapClientImpl) scope.getSession().getSqlMapClient()) .getDelegate().isForceMultipleResultSetSupport(); } private void handleResults(StatementScope statementScope, ResultSet rs, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException { try { statementScope.setResultSet(rs); ResultMap resultMap = statementScope.getResultMap(); if (resultMap != null) { // Skip Results if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) { if (skipResults > 0) { rs.absolute(skipResults); } } else { for (int i = 0; i < skipResults; i++) { if (!rs.next()) { return; } } } // Get Results int resultsFetched = 0; while ((maxResults == SqlExecutor.NO_MAXIMUM_RESULTS || resultsFetched < maxResults) && rs.next()) { Object[] columnValues = resultMap.resolveSubMap( statementScope, rs).getResults(statementScope, rs); callback.handleResultObject(statementScope, columnValues, rs); resultsFetched++; } } } finally { statementScope.setResultSet(null); } } private void retrieveOutputParameters(StatementScope statementScope, CallableStatement cs, ParameterMapping[] mappings, Object[] parameters, RowHandlerCallback callback) throws SQLException { for (int i = 0; i < mappings.length; i++) { ParameterMapping mapping = ((ParameterMapping) mappings[i]); if (mapping.isOutputAllowed()) { if ("java.sql.ResultSet".equalsIgnoreCase(mapping .getJavaTypeName())) { ResultSet rs = (ResultSet) cs.getObject(i + 1); ResultMap resultMap; if (mapping.getResultMapName() == null) { resultMap = statementScope.getResultMap(); handleOutputParameterResults(statementScope, resultMap, rs, callback); } else { SqlMapClientImpl client = (SqlMapClientImpl) statementScope .getSession().getSqlMapClient(); resultMap = client.getDelegate().getResultMap( mapping.getResultMapName()); DefaultRowHandler rowHandler = new DefaultRowHandler(); RowHandlerCallback handlerCallback = new RowHandlerCallback( resultMap, null, rowHandler); handleOutputParameterResults(statementScope, resultMap, rs, handlerCallback); parameters[i] = rowHandler.getList(); } rs.close(); } else { parameters[i] = mapping.getTypeHandler().getResult(cs, i + 1); } } } } private void registerOutputParameters(CallableStatement cs, ParameterMapping[] mappings) throws SQLException { for (int i = 0; i < mappings.length; i++) { ParameterMapping mapping = ((ParameterMapping) mappings[i]); if (mapping.isOutputAllowed()) { if (null != mapping.getTypeName() && !mapping.getTypeName().equals("")) { // @added cs.registerOutParameter(i + 1, mapping.getJdbcType(), mapping.getTypeName()); } else { if (mapping.getNumericScale() != null && (mapping.getJdbcType() == Types.NUMERIC || mapping .getJdbcType() == Types.DECIMAL)) { cs.registerOutParameter(i + 1, mapping.getJdbcType(), mapping.getNumericScale().intValue()); } else { cs.registerOutParameter(i + 1, mapping.getJdbcType()); } } } } } private void handleOutputParameterResults(StatementScope statementScope, ResultMap resultMap, ResultSet rs, RowHandlerCallback callback) throws SQLException { ResultMap orig = statementScope.getResultMap(); try { statementScope.setResultSet(rs); if (resultMap != null) { statementScope.setResultMap(resultMap); // Get Results while (rs.next()) { Object[] columnValues = resultMap.resolveSubMap( statementScope, rs).getResults(statementScope, rs); callback.handleResultObject(statementScope, columnValues, rs); } } } finally { statementScope.setResultSet(null); statementScope.setResultMap(orig); } } /** * Clean up any batches on the session * * @param sessionScope * - the session to clean up */ public void cleanup(SessionScope sessionScope) { Batch batch = (Batch) sessionScope.getBatch(); if (batch != null) { batch.cleanupBatch(sessionScope); sessionScope.setBatch(null); } } private PreparedStatement prepareStatement(SessionScope sessionScope, Connection conn, String sql, Integer rsType) throws SQLException { SqlMapExecutorDelegate delegate = ((SqlMapClientImpl) sessionScope .getSqlMapExecutor()).getDelegate(); if (sessionScope.hasPreparedStatementFor(sql)) { return sessionScope.getPreparedStatement((sql)); } else { PreparedStatement ps = conn.prepareStatement(sql, rsType.intValue(), ResultSet.CONCUR_READ_ONLY); sessionScope.putPreparedStatement(delegate, sql, ps); return ps; } } private CallableStatement prepareCall(SessionScope sessionScope, Connection conn, String sql, Integer rsType) throws SQLException { SqlMapExecutorDelegate delegate = ((SqlMapClientImpl) sessionScope .getSqlMapExecutor()).getDelegate(); if (sessionScope.hasPreparedStatementFor(sql)) { return (CallableStatement) sessionScope.getPreparedStatement((sql)); } else { CallableStatement cs = conn.prepareCall(sql, rsType.intValue(), ResultSet.CONCUR_READ_ONLY); sessionScope.putPreparedStatement(delegate, sql, cs); return cs; } } private static PreparedStatement prepareStatement( SessionScope sessionScope, Connection conn, String sql) throws SQLException { SqlMapExecutorDelegate delegate = ((SqlMapClientImpl) sessionScope .getSqlMapExecutor()).getDelegate(); if (sessionScope.hasPreparedStatementFor(sql)) { return sessionScope.getPreparedStatement((sql)); } else { PreparedStatement ps = conn.prepareStatement(sql); sessionScope.putPreparedStatement(delegate, sql, ps); return ps; } } private CallableStatement prepareCall(SessionScope sessionScope, Connection conn, String sql) throws SQLException { SqlMapExecutorDelegate delegate = ((SqlMapClientImpl) sessionScope .getSqlMapExecutor()).getDelegate(); if (sessionScope.hasPreparedStatementFor(sql)) { return (CallableStatement) sessionScope.getPreparedStatement((sql)); } else { CallableStatement cs = conn.prepareCall(sql); sessionScope.putPreparedStatement(delegate, sql, cs); return cs; } } private static void closeStatement(SessionScope sessionScope, PreparedStatement ps) { if (ps != null) { if (!sessionScope.hasPreparedStatement(ps)) { try { ps.close(); } catch (SQLException e) { // ignore } } } } /** * @param rs */ private static void closeResultSet(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { // ignore } } } private static void setStatementTimeout(MappedStatement mappedStatement, Statement statement) throws SQLException { if (mappedStatement.getTimeout() != null) { statement.setQueryTimeout(mappedStatement.getTimeout().intValue()); } } // // Inner Classes // private static class Batch { private String currentSql; private List statementList = new ArrayList(); private List batchResultList = new ArrayList(); private int size; /** * Create a new batch */ public Batch() { this.size = 0; } /** * Getter for the batch size * * @return - the batch size */ public int getSize() { return size; } /** * Add a prepared statement to the batch * * @param statementScope * - the request scope * @param conn * - the database connection * @param sql * - the SQL to add * @param parameters * - the parameters for the SQL * @throws SQLException * - if the prepare for the SQL fails */ public void addBatch(StatementScope statementScope, Connection conn, String sql, Object[] parameters) throws SQLException { PreparedStatement ps = null; if (currentSql != null && currentSql.equals(sql)) { int last = statementList.size() - 1; ps = (PreparedStatement) statementList.get(last); } else { ps = prepareStatement(statementScope.getSession(), conn, sql); setStatementTimeout(statementScope.getStatement(), ps); currentSql = sql; statementList.add(ps); batchResultList.add(new BatchResult(statementScope .getStatement().getId(), sql)); } statementScope.getParameterMap().setParameters(statementScope, ps, parameters); ps.addBatch(); size++; } /** * TODO (Jeff Butler) - maybe this method should be deprecated in some * release, and then removed in some even later release. * executeBatchDetailed gives much more complete information. <p/> * Execute the current session's batch * * @return - the number of rows updated * @throws SQLException * - if the batch fails */ public int executeBatch() throws SQLException { int totalRowCount = 0; for (int i = 0, n = statementList.size(); i < n; i++) { PreparedStatement ps = (PreparedStatement) statementList.get(i); int[] rowCounts = ps.executeBatch(); for (int j = 0; j < rowCounts.length; j++) { if (rowCounts[j] == Statement.SUCCESS_NO_INFO) { // do nothing } else if (rowCounts[j] == Statement.EXECUTE_FAILED) { throw new SQLException( "The batched statement at index " + j + " failed to execute."); } else { totalRowCount += rowCounts[j]; } } } return totalRowCount; } /** * Batch execution method that returns all the information the driver * has to offer. * * @return a List of BatchResult objects * @throws BatchException * (an SQLException sub class) if any nested batch fails * @throws SQLException * if a database access error occurs, or the drive does not * support batch statements * @throws BatchException * if the driver throws BatchUpdateException */ public List executeBatchDetailed() throws SQLException, BatchException { List answer = new ArrayList(); for (int i = 0, n = statementList.size(); i < n; i++) { BatchResult br = (BatchResult) batchResultList.get(i); PreparedStatement ps = (PreparedStatement) statementList.get(i); try { br.setUpdateCounts(ps.executeBatch()); } catch (BatchUpdateException e) { StringBuffer message = new StringBuffer(); message.append("Sub batch number "); message.append(i + 1); message.append(" failed."); if (i > 0) { message.append(" "); message.append(i); message .append(" prior sub batch(s) completed successfully, but will be rolled back."); } throw new BatchException(message.toString(), e, answer, br .getStatementId(), br.getSql()); } answer.add(br); } return answer; } /** * Close all the statements in the batch and clear all the statements * * @param sessionScope */ public void cleanupBatch(SessionScope sessionScope) { for (int i = 0, n = statementList.size(); i < n; i++) { PreparedStatement ps = (PreparedStatement) statementList.get(i); closeStatement(sessionScope, ps); } currentSql = null; statementList.clear(); batchResultList.clear(); size = 0; } } private void setupResultObjectFactory(StatementScope statementScope) { SqlMapClientImpl client = (SqlMapClientImpl) statementScope .getSession().getSqlMapClient(); ResultObjectFactoryUtil.setResultObjectFactory(client .getResultObjectFactory()); ResultObjectFactoryUtil.setStatementId(statementScope.getStatement() .getId()); } }
Dialect.java
package com.ibatis.sqlmap.engine.execution; public class Dialect { private static final String SQL_END_DELIMITER = ";"; public static String getLimitString(String dbName, String sql, int offset, int limit) { String limitString = sql; if (dbName.toLowerCase().indexOf("mysql") != -1) { limitString = getMysqlLimitString(sql, offset, limit); } if (dbName.toLowerCase().indexOf("microsoft sql server") != -1) { limitString = getMssqlLimitString(sql, offset, limit); } if (dbName.toLowerCase().indexOf("oracle") != -1) { limitString = getOracleLimitString(sql, offset, limit); } if (dbName.toLowerCase().indexOf("db2") != -1) { limitString = getDB2LimitString(sql, offset, limit); } return limitString; } private static String getMysqlLimitString(String sql, int offset, int limit) { sql = trim(sql); StringBuffer sb = new StringBuffer(sql.length() + 20); sb.append(sql); if (offset > 0) { sb.append(" limit ").append(offset).append(',').append(limit); } else { sb.append(" limit ").append(limit); } return sb.toString(); } private static String getOracleLimitString(String sql, int offset, int limit) { sql = trim(sql); StringBuffer sb = new StringBuffer(sql.length() + 100); if (offset > 0) { sb.append("select * from ( select row_.*, rownum rownum_ from ( ") .append(sql).append(" ) row_ where rownum <= ").append( offset + limit).append(") where rownum_ > ") .append(offset); } else { sb.append("select * from ( ").append(sql).append( " ) where rownum <= ").append(limit); } return sb.toString(); } private static String getMssqlLimitString(String sql, int offset, int limit) { return null; } private static String getDB2LimitString(String sql, int offset, int limit) { return null; } private static String trim(String sql) { sql = sql.trim(); if (sql.endsWith(SQL_END_DELIMITER)) { sql = sql.substring(0, sql.length() - 1 - SQL_END_DELIMITER.length()); } return sql; } }
评论
2 楼
di1984HIT
2013-07-15
写的不错,呵呵。学习学习了
1 楼
atgoingguoat
2010-03-28
没这么复杂吧?
我操作简单.
我简单写下我的代码:
持久化接口
public interface BlackMobileInfoDao {
/**
* 分页查询 信息
* @param map Map
* @return List
*/
List queryPageBlackMobileInfo(Map map);
/**
* 当前 总记录
* @param map Map
* @return int
*/
public int queryPageBlackMobileInfoCount(Map map);
.............
}
持久化实现类
public class BlackMobileInfoSqlMapDao extends BaseSqlMapDao implements BlackMobileInfoDao{
/**
* 分页查询 信息
* @param map Map
* @return List
*/
public List queryPageBlackMobileInfo(Map map) {
int startRow =(Integer)map.get("startRow");
int pageSize =(Integer)map.get("pageSize");
List list = null;
try {
if(pageSize==0){
list = queryForList("queryPageBlackMobileInfo", map);
}else{
list = queryForList("queryPageBlackMobileInfo", map, startRow,
pageSize);
}
}catch(Exception e ) {
log.error(e);
}
return list;
}
public int queryPageBlackMobileInfoCount(Map map) {
int count = 0;
try {
count = (Integer)queryForObject("queryPageBlackMobileInfoCount",map);
}catch(Exception e ) {
log.error(e);
}
return count;
}
...
}
ibatis 服务类
public class BlackMobileInfoService implements ServiceBean {
private static Log log = LogFactory.getLog(CancelCommandInfoService.class);
private static BlackMobileInfoService instance = null;
private DaoManager daoManager = null;
private BlackMobileInfoDao blackMobileInfoDao;
private BlackMobileInfoService() {
daoManager = DaoConfig.getDaomanager();
blackMobileInfoDao =(BlackMobileInfoDao)daoManager.getDao(BlackMobileInfoDao.class);
}
public static BlackMobileInfoService getInstance() {
if(instance == null) {
instance = new BlackMobileInfoService();
}
return instance;
}
/**
* 多条件 分页查询 信息
* @param compID String
* @param empID String
* @param mobile String
* @param mobileType String
* @param startRow int
* @param pageSize int
* @return List
* 增
*/
public List queryPageBlackMobileInfo(String compID,String empID,String mobile,String mobileType,int startRow,int pageSize) {
Map map = new HashMap();
map.put("mobile",mobile);
map.put("empID",empID);
map.put("mobileType",mobileType);
map.put("compID",compID);
map.put("startRow",startRow);
map.put("pageSize",pageSize);
return blackMobileInfoDao.queryPageBlackMobileInfo(map);
}
/**
* 多条件 分页查询 记录总数
* @param compID String
* @param empID String
* @param mobile String
* @param mobileType String
* @return int
*
*/
public int queryPageBlackMobileInfoCount(String compID,String empID,String mobile,String mobileType) {
Map map = new HashMap();
map.put("mobile",mobile);
map.put("empID",empID);
map.put("mobileType",mobileType);
map.put("compID",compID);
return blackMobileInfoDao.queryPageBlackMobileInfoCount(map);
}
.........
外部调用:
blackMobile.initBlackMobileInfo(compID,'','','',(currentPage-1)* pageSize,pageSize);
有点散,我空间有ibatis 示例.下载看下.
我操作简单.
我简单写下我的代码:
持久化接口
public interface BlackMobileInfoDao {
/**
* 分页查询 信息
* @param map Map
* @return List
*/
List queryPageBlackMobileInfo(Map map);
/**
* 当前 总记录
* @param map Map
* @return int
*/
public int queryPageBlackMobileInfoCount(Map map);
.............
}
持久化实现类
public class BlackMobileInfoSqlMapDao extends BaseSqlMapDao implements BlackMobileInfoDao{
/**
* 分页查询 信息
* @param map Map
* @return List
*/
public List queryPageBlackMobileInfo(Map map) {
int startRow =(Integer)map.get("startRow");
int pageSize =(Integer)map.get("pageSize");
List list = null;
try {
if(pageSize==0){
list = queryForList("queryPageBlackMobileInfo", map);
}else{
list = queryForList("queryPageBlackMobileInfo", map, startRow,
pageSize);
}
}catch(Exception e ) {
log.error(e);
}
return list;
}
public int queryPageBlackMobileInfoCount(Map map) {
int count = 0;
try {
count = (Integer)queryForObject("queryPageBlackMobileInfoCount",map);
}catch(Exception e ) {
log.error(e);
}
return count;
}
...
}
ibatis 服务类
public class BlackMobileInfoService implements ServiceBean {
private static Log log = LogFactory.getLog(CancelCommandInfoService.class);
private static BlackMobileInfoService instance = null;
private DaoManager daoManager = null;
private BlackMobileInfoDao blackMobileInfoDao;
private BlackMobileInfoService() {
daoManager = DaoConfig.getDaomanager();
blackMobileInfoDao =(BlackMobileInfoDao)daoManager.getDao(BlackMobileInfoDao.class);
}
public static BlackMobileInfoService getInstance() {
if(instance == null) {
instance = new BlackMobileInfoService();
}
return instance;
}
/**
* 多条件 分页查询 信息
* @param compID String
* @param empID String
* @param mobile String
* @param mobileType String
* @param startRow int
* @param pageSize int
* @return List
* 增
*/
public List queryPageBlackMobileInfo(String compID,String empID,String mobile,String mobileType,int startRow,int pageSize) {
Map map = new HashMap();
map.put("mobile",mobile);
map.put("empID",empID);
map.put("mobileType",mobileType);
map.put("compID",compID);
map.put("startRow",startRow);
map.put("pageSize",pageSize);
return blackMobileInfoDao.queryPageBlackMobileInfo(map);
}
/**
* 多条件 分页查询 记录总数
* @param compID String
* @param empID String
* @param mobile String
* @param mobileType String
* @return int
*
*/
public int queryPageBlackMobileInfoCount(String compID,String empID,String mobile,String mobileType) {
Map map = new HashMap();
map.put("mobile",mobile);
map.put("empID",empID);
map.put("mobileType",mobileType);
map.put("compID",compID);
return blackMobileInfoDao.queryPageBlackMobileInfoCount(map);
}
.........
外部调用:
blackMobile.initBlackMobileInfo(compID,'','','',(currentPage-1)* pageSize,pageSize);
有点散,我空间有ibatis 示例.下载看下.
相关推荐
标题中的“ibatis分页”指的是在使用iBATIS(一个SQL映射框架)时,如何实现数据库查询结果的分页显示。iBATIS通过XML配置文件或注解方式将Java代码与SQL语句分离,提供了更灵活的数据库操作方式。在处理大量数据时...
标题"ibatis分页功能"指的就是如何在iBATIS框架中实现数据库查询的分页效果。分页不仅提高了用户体验,还能减少不必要的数据库负载。 描述中提到,分页功能是通过`page.tld`标签实现的。`tld`文件是JSP Tag Library...
本文将深入探讨Ibatis实现分页的相关知识点,并基于提供的标签“源码”和“工具”,分享如何在实际项目中运用Ibatis进行分页处理。 首先,了解Ibatis的基本概念。Ibatis是由Apache基金会维护的一个开源项目,它是一...
iBatis分页源代码解析.chm,ibatis介绍等
本知识点将深入探讨如何在Struts2框架中结合iBatis实现基于Freemarker模板的分页功能。 首先,我们需要理解iBatis,它是一个轻量级的Java持久层框架,它提供了一个SQL映射框架,允许开发者将SQL语句与Java代码分离...
公司的大部分项目都开始使用IBatis作为O/R Mapping了,但是在使用的过程中也发现了很多不方便和存在争议的地方,其中一个不方便的地方就是分页,目前的处理方式都是在sqlMap中写针对特定数据库的物理分页Sql语句,对于...
### ibatis分页技术详解与应用 在软件开发领域,特别是在数据库操作中,分页是一项极为常见的需求。分页不仅可以优化用户体验,减少加载时间,还能有效地管理大量的数据查询结果。Ibatis,作为一款优秀的持久层框架...
本篇文章将深入探讨如何在Xwork和iBatis的集成应用中实现分页功能,让开发者能够更高效地处理大量数据。 首先,让我们了解什么是分页。分页是网页显示大量数据时常用的一种技术,它将结果集分割成若干小部分(页)...
在传统的iBatis框架中,分页通常采用逻辑分页的方式,即通过游标(ResultSet)来逐条处理数据,从而实现分页效果。这种方式虽然跨数据库兼容性好,但性能上不如数据库原生的物理分页高效。物理分页是直接在SQL语句中...
三、Ibatis分页实现 1. SQL配置 在Ibatis的Mapper XML文件中,我们需要编写一个带有参数的SQL查询,这些参数通常包括当前页码和每页记录数。例如: ```xml SELECT * FROM your_table != null and pageSize != ...
本项目基于ibatis框架实现了分页功能,覆盖了从底层数据库操作到页面展示的完整流程,包括DAO层、Service层、Action层以及JSP页面的展示。 首先,我们来了解一下什么是ibatis。Ibatis是一个优秀的持久层框架,它...
ibatis_likehbm高效分页组件ibatis_likehbm高效分页组件ibatis_likehbm高效分页组件ibatis_likehbm高效分页组件ibatis_likehbm高效分页组件ibatis_likehbm高效分页组件 ibatis_likehbm高效分页组件 ibatis_likehbm...
在2.3.4这个版本中,Ibatis 提供了数据库无关的分页功能,这是一种在不依赖特定数据库语法的情况下实现分页查询的方法,有助于提高代码的可移植性和维护性。 数据库无关分页的核心思想是将分页参数(如当前页数和每...
NULL 博文链接:https://jsufly.iteye.com/blog/508249
你可以定义一个Mapper接口和XML配置文件,编写SQL查询来获取指定页码的数据,并通过iBatis的参数映射功能传入分页参数。 文件列表中的`.classpath`和`.project`是Eclipse或类似的IDE的项目配置文件,它们定义了项目...
本项目"ibatis_with_memcached"就是关于如何将Ibatis与Memcached集成,实现高效的数据库缓存策略的实例。 Ibatis是一个基于Java的SQL映射框架,它允许开发者编写SQL语句并与Java对象进行绑定,从而避免了传统的JDBC...
ibatis 物理分页jar ,与官方ibatis不冲突,可直接使用。
"iBatis分页"是数据库操作中常见的需求,iBatis提供了方便的分页支持。在学习这部分时,你会了解如何在SQL中添加分页条件,以及如何在Java代码中处理分页结果。 "spring+iBatis处理1对多数据表实例"展示了如何将...
Ibatis.NET提供了分页查询的实现,下面我们将深入探讨如何在Ibatis.NET中实现分页。 首先,理解分页的基本概念。分页通常涉及两个关键参数:当前页码(Page Number)和每页记录数(PageSize)。例如,如果当前页码...
Ibatis SQLServerDialect 2008 分页 可实现SQLServerDialect 分页 支持ibatis3