通用分页的核心代码

通用分页的核心代码

package com.zhoujun.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
		/**
		 * 内部接口 专门用来遍历rs结果集
		 * @author 周俊
		 *
		 * @param 
		 */
public class BaseDAO<K> {
	public static interface CallBack<T> {
		public List<T> forEachRs(ResultSet rs) throws SQLException;
	}

	public List<K> exectueQuery(String sql,PageBean pageBean,CallBack callBack)  {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			con = DBHelper.getConnection();
			//查询符合条件的总记录
			if(null!=pageBean && pageBean.isPagination()) {
				String countSql = this.getCountSql(sql);
				ps = con.prepareStatement(countSql);
				rs = ps.executeQuery();
				if(rs.next()) {
					Object obj = rs.getInt(1);
					pageBean.setTotal(obj.toString());
				}
				DBHelper.close(null, ps, rs);
				
			}
			
			//2.查询符合条件的记录
			if(null!=pageBean && pageBean.isPagination()) {
				sql = this.pageSql(sql, pageBean);
			}
			
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			
			
			return callBack.forEachRs(rs);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			DBHelper.close(con, ps, rs);
		}
		
		
	}
	/**
	 * 得到查询总记录的sql语句
	 * @param sql
	 * @return
	 */
	private String getCountSql(String sql) {
		
		String countSql = "select count(*) from ("+ sql +")t1";
		
		return countSql;
	}
	
	/**
	 * 得到分页的sql语句
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String pageSql(String sql,PageBean pageBean) {
		
		String pageSql = sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
		
		return pageSql;
	}
}

总结:重要的部分要搞懂

你可能感兴趣的:(通用分页的核心代码)