⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqlexecutor.java

📁 本套系统采用了业界当前最为流行的beanAction组件
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 *  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 com.ibatis.sqlmap.engine.mapping.parameter.BasicParameterMapping;
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.MappedStatement;
import com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback;
import com.ibatis.sqlmap.engine.scope.ErrorContext;
import com.ibatis.sqlmap.engine.scope.RequestScope;
import com.ibatis.sqlmap.engine.scope.SessionScope;
import com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient;
import com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate;
import com.ibatis.sqlmap.engine.mapping.statement.DefaultRowHandler;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Class responsible for executing the SQL
 */
public class SqlExecutor {

  //
  // 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 Methods
  //

  /**
   * Execute an update
   *
   * @param request    - 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(RequestScope request, Connection conn, String sql, Object[] parameters) throws SQLException {
    ErrorContext errorContext = request.getErrorContext();
    errorContext.setActivity("executing update");
    errorContext.setObjectId(sql);
    PreparedStatement ps = null;
    setupResultObjectFactory(request);
    int rows = 0;
    try {
      errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");
      ps = prepareStatement(request.getSession(), conn, sql);
      setStatementTimeout(request.getStatement(), ps);
      errorContext.setMoreInfo("Check the parameters (set parameters failed).");
      request.getParameterMap().setParameters(request, ps, parameters);
      errorContext.setMoreInfo("Check the statement (update failed).");
      ps.execute();
      rows = ps.getUpdateCount();
    } finally {
      closeStatement(request.getSession(), ps);
    }
    return rows;
  }

  /**
   * Adds a statement to a batch
   *
   * @param request    - 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(RequestScope request, Connection conn, String sql, Object[] parameters) throws SQLException {
    Batch batch = (Batch) request.getSession().getBatch();
    if (batch == null) {
      batch = new Batch();
      request.getSession().setBatch(batch);
    }
    batch.addBatch(request, conn, sql, parameters);
  }

  /**
   * Execute a batch of statements
   *
   * @param session - the session scope
   * @return - the number of rows impacted by the batch
   * @throws SQLException - if a statement fails
   */
  public int executeBatch(SessionScope session) throws SQLException {
    int rows = 0;
    Batch batch = (Batch) session.getBatch();
    if (batch != null) {
      try {
        rows = batch.executeBatch();
      } finally {
        batch.cleanupBatch(session);
      }
    }
    return rows;
  }

  /**
   * Execute a batch of statements
   *
   * @param session - 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 session) throws SQLException, BatchException {
    List answer = null;
    Batch batch = (Batch) session.getBatch();
    if (batch != null) {
      try {
        answer = batch.executeBatchDetailed();
      } finally {
        batch.cleanupBatch(session);
      }
    }
    return answer;
  }

  /**
   * Long form of the method to execute a query
   *
   * @param request     - 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
   */
  public void executeQuery(RequestScope request, Connection conn, String sql, Object[] parameters, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException {
    ErrorContext errorContext = request.getErrorContext();
    errorContext.setActivity("executing query");
    errorContext.setObjectId(sql);
    PreparedStatement ps = null;
    ResultSet rs = null;
    setupResultObjectFactory(request);
    try {
      errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");
      Integer rsType = request.getStatement().getResultSetType();
      if (rsType != null) {
        ps = prepareStatement(request.getSession(), conn, sql, rsType);
      } else {
        ps = prepareStatement(request.getSession(), conn, sql);
      }
      setStatementTimeout(request.getStatement(), ps);
      Integer fetchSize = request.getStatement().getFetchSize();
      if (fetchSize != null) {
        ps.setFetchSize(fetchSize.intValue());
      }
      errorContext.setMoreInfo("Check the parameters (set parameters failed).");
      request.getParameterMap().setParameters(request, 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, request, skipResults, maxResults, callback);
      // End ResultSet Handling
    } finally {
      try {
        closeResultSet(rs);
      } finally {
        closeStatement(request.getSession(), ps);
      }
    }

  }

  /**
   * Execute a stored procedure that updates data
   *
   * @param request    - 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(RequestScope request, Connection conn, String sql, Object[] parameters) throws SQLException {
    ErrorContext errorContext = request.getErrorContext();
    errorContext.setActivity("executing update procedure");
    errorContext.setObjectId(sql);
    CallableStatement cs = null;
    setupResultObjectFactory(request);
    int rows = 0;
    try {
      errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");
      cs = prepareCall(request.getSession(), conn, sql);
      setStatementTimeout(request.getStatement(), cs);
      ParameterMap parameterMap = request.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(request, 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(request, cs, mappings, parameters, null);
    } finally {
      closeStatement(request.getSession(), cs);
    }
    return rows;
  }

  /**
   * Execute a stored procedure
   *
   * @param request     - 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(RequestScope request, Connection conn, String sql, Object[] parameters, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException {
    ErrorContext errorContext = request.getErrorContext();
    errorContext.setActivity("executing query procedure");
    errorContext.setObjectId(sql);
    CallableStatement cs = null;
    ResultSet rs = null;
    setupResultObjectFactory(request);
    try {
      errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");
      Integer rsType = request.getStatement().getResultSetType();
      if (rsType != null) {
        cs = prepareCall(request.getSession(), conn, sql, rsType);
      } else {
        cs = prepareCall(request.getSession(), conn, sql);
      }
      setStatementTimeout(request.getStatement(), cs);
      Integer fetchSize = request.getStatement().getFetchSize();
      if (fetchSize != null) {
        cs.setFetchSize(fetchSize.intValue());
      }
      ParameterMap parameterMap = request.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(request, 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, request, skipResults, maxResults, callback);
      // End ResultSet Handling
      errorContext.setMoreInfo("Check the output parameters (retrieval of output parameters failed).");
      retrieveOutputParameters(request, cs, mappings, parameters, callback);

    } finally {
      try {
        closeResultSet(rs);
      } finally {
        closeStatement(request.getSession(), cs);
      }
    }
  }

  private ResultSet handleMultipleResults(PreparedStatement ps, RequestScope request, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException {
    ResultSet rs;
    rs = getFirstResultSet(ps);
    if (rs != null) {
      handleResults(request, rs, skipResults, maxResults, callback);
    }

    // Multiple ResultSet handling
    if (callback.getRowHandler() instanceof DefaultRowHandler) {
      MappedStatement statement = request.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(ps)) {
          if (i >= resultMaps.length) break;
          ResultMap rm = resultMaps[i];
          request.setResultMap(rm);
          rs = ps.getResultSet();
          DefaultRowHandler rh = new DefaultRowHandler();
          handleResults(request, rs, skipResults, maxResults, new RowHandlerCallback(rm, null, rh));
          multipleResults.add(rh.getList());
          i++;
        }
        defaultRowHandler.setList(multipleResults);
        request.setResultMap(statement.getResultMap());
      } else {
        while (moveToNextResultsSafely(ps)) ;
      }
    }
    // End additional ResultSet handling
    return rs;
  }

  private ResultSet getFirstResultSet(Statement stmt) throws SQLException {
    ResultSet rs = null;
    boolean hasMoreResults = true;
    while (hasMoreResults) {
      rs = stmt.getResultSet();
      if (rs != null) {
        break;
      }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -