공통 페이지 나누기 핵심 코드

10354 단어

공통 페이지 나누기 핵심 코드

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;
	}
}


요약: 중요한 부분은 이해해야 한다

좋은 웹페이지 즐겨찾기