Java tutorial
/* * Copyright (c) 2012-2013, Poplar Yfyang ?? (poplar1123@gmail.com). 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.gj.test.base.paginator.mybatis; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.log4j.Logger; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author poplar.yfyang * @author miemiedev */ public class SQLHelp { private static Logger logger = Logger.getLogger(SQLHelp.class); /** * * * @param sql SQL? * @param mappedStatement mapped * @param parameterObject ? * @param boundSql boundSql * @param dialect database dialect * @return * @throws SQLException sql */ public static int getCount(final String sql, final MappedStatement mappedStatement, final Object parameterObject, final BoundSql boundSql, Dialect dialect) throws SQLException { final String count_sql = dialect.getCountString(sql); logger.debug("Total count SQL [{" + count_sql + "}] "); logger.debug("Total count Parameters: {" + parameterObject + "} "); Connection connection = null; PreparedStatement countStmt = null; ResultSet rs = null; try { connection = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection(); countStmt = connection.prepareStatement(count_sql); final BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), count_sql, boundSql.getParameterMappings(), parameterObject); // Field metaParamsField = ReflectUtil.getFieldByFieldName(boundSql, "metaParameters"); // if (metaParamsField != null) { // MetaObject mo = (MetaObject) ReflectUtil.getValueByFieldName(boundSql, "metaParameters"); // ReflectUtil.setValueByFieldName(countBS, "metaParameters", mo); // } // setParameters(prepStat, configuration, countBS, parameterObject); // DefaultParameterHandler handler = new DefaultParameterHandler(mappedStatement, parameterObject, countBS); handler.setParameters(countStmt); rs = countStmt.executeQuery(); int count = 0; if (rs.next()) { count = rs.getInt(1); } logger.debug("Total count: {" + count + "}"); return count; } finally { try { if (rs != null) { rs.close(); } } finally { try { if (countStmt != null) { countStmt.close(); } } finally { if (connection != null && !connection.isClosed()) { connection.close(); } } } } } }