- 在开发项目中需要使用到查询分页的时候然后需要写一个Dao层和对应的方法
- 结果ADao层的代码写好了,然后又来一个需求也要查询分页又要写一个
BDdao层这样太麻烦了类似这就是重复了,其实涂涂改改就好了
- 我们就可以利用相同的代码,让它们相同的代码放在一起,然而这就是如何偷懒…
1.目的:作用通用的分页查询方法
它主要实现的就是通用,将普通查询方法进行反射优化,转变成一个可以被所有实体类dao层所继承的通用查询方法。
2.思路:
1、将原有的查询向上抽取
2、让返回值变成泛型
3、使用回调函数处理resultset
4、利用反射处理回调函数
5、获取总记录数(页面展示,计算总页数)
6、拼接分页sql语句,获取对应的结果集
package com.houzhihong.paging.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 提供了一组获得或关闭数据库对象的方法
*
*/
public class DBAccess {
private static String driver;
private static String url;
private static String user;
private static String password;
static {// 静态块执行一次,加载 驱动一次
try {
InputStream is = DBAccess.class
.getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("pwd");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 获得数据连接对象
*
* @return
*/
public static Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Statement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(conn);
}
public static boolean isOracle() {
return "oracle.jdbc.driver.OracleDriver".equals(driver);
}
public static boolean isSQLServer() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
}
public static boolean isMysql() {
return "com.mysql.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println("数据库连接(关闭)成功");
}
}
3.直接可以通过这个config.properties
文件链接到分别要使用的数据库
4.测试是否连接数据库成功(连接成功)
5.判断字符串是否为空的工具类
package com.houzhihong.paging.util;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
6.为了防止中文乱码专门写一个处理类
package com.houzhihong.paging.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中文乱码处理
*
*/
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 默认字符集
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
Set set = map.keySet();// 取出所有参数名
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
7.为了简化代码写一个PageBean工具类
pagination
决定是否要分页,相当于开关.
private boolean pagination = true;//是否分页 默认分页
package com.houzhihong.paging.util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
public class PageBean {
private int page =1;//页码
private int rows =10;//页的大小
private int total = 0;//总记录数 从数据库中进行统计的
private boolean pagination = true;//是否分页 默认分页
private String url;//请求路径
//存储页面传的 参数
private Map<String, String[]> ParameterMap = new HashMap<String, String[]>();
//专门写一个方法,用来做pageBean的初始化
public void setRequest(HttpServletRequest request) {
// page rows pagination 公关参数 只能做分页
//从界面获取到分页的参数
String page= request.getParameter("page");
String rows= request.getParameter("rows");
String pagination = request.getParameter("pagination");
//给参数赋值
this.setPage(page);
this.setRows(rows);
this.setPagination(pagination);
//获取请求路径
this.url=request.getContextPath()+request.getServletPath();
//获取界面传递的参数
this.ParameterMap =request.getParameterMap();
}
/**
* 上一页
* @return
*/
public int getPreviousPage() {
int previousPage=this.page-1;
if(0 == previousPage) {
previousPage =1;
}
return previousPage;
}
/**
* 下一页
* @return
*/
public int getNextPage() {
int nextPage=this.page+1;
if(nextPage>getMaxPage()) {
nextPage=getMaxPage();
}
return nextPage;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
if(null!=page && !"".equals(page.trim())){
this.page =Integer.parseInt(page);
}
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public void setRows(String rows) {
if(null!=rows && !"".equals(rows.trim())){
this.rows =Integer.parseInt(rows);
}
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
public void setPagination(String pagination) {
if("false".equals(pagination)) {
this.pagination = Boolean.parseBoolean(pagination);
}
}
public PageBean() {
super();
}
/**
* 获得启始记录的下标
* @return
*/
public int getStartsIndex() {
return (this.page-1)*this.rows;
}
/**
* 获取最大页数
* @return
*/
public int getMaxPage() {
int maxPage =this.total/this.rows;
if(0!=this.total%this.rows) {
maxPage=maxPage+1;
}
return maxPage;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameterMap() {
return ParameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
ParameterMap = parameterMap;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
8.dao类后面会通过简化代码去继承BaseDao改成一个通用的分页
package com.houzhihong.paging.dao;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.my.test.entity.Student;
import com.my.test.util.DBAccess;
import com.my.test.util.PageBean;
import com.my.test.util.StringUtils;
public class StudentDao extends BaseDao<Student> implements Serializable {
private static final long serialVersionUID = 945294532039568659L;
/**
* 增加方法
* @param student
*/
public void add(Student student) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "insert into t_student (sname,sname_pinyin,age,remark) values(?,?,?,?) ";
try {
con = DBAccess.getConnection();
ps = con.prepareStatement(sql);
ps.setString(1, student.getSname());
ps.setString(2, student.getSname_pinyin());
ps.setInt(3, student.getAge());
ps.setString(4, student.getRemartk());
ps.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
DBAccess.close(con, ps, rs);
}
}
/**
* 查询所有 模糊查询
* @param student
* @return
*/
public List<Student> find(Student student){
List<Student> stuList = new ArrayList<Student>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select * from t_student where 1=1 ";
if(StringUtils.isNotBlank(student.getSname())) {
sql+=" and (sname like'%"+student.getSname()+"%' or sname_pinyin like '%"+student.getSname()+"%')";
}
System.out.println(sql);
try {
con = DBAccess.getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
Student stu = null;
while(rs.next()) {
stu = new Student();
stu.setSid(rs.getInt("sid"));
stu.setSname(rs.getString("sname"));
stu.setSname_pinyin(rs.getString("sname_pinyin"));
stu.setAge(rs.getInt("age"));
stu.setRemartk(rs.getString("remartk"));
stuList.add(stu);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
DBAccess.close(con, ps, rs);
}
return stuList;
}
public List<Student> find(Student student,PageBean pageBean){
List<Student> stuList = new ArrayList<Student>();
String sql = "select * from t_student where 1=1 ";
if(StringUtils.isNotBlank(student.getSname())) {
sql+=" and sname like'%"+student.getSname()+"%' or sname_pinyin like '%"+student.getSname()+"%'";
}
return this.executeQuery(sql, pageBean, new Callback<Student>() {
@Override
public List<Student> foreach(ResultSet rs) throws SQLException {
List<Student> stuList = new ArrayList<Student>();
Student stu = null;
while(rs.next()) {
stu = new Student();
stu.setSid(rs.getInt("sid"));
stu.setSname(rs.getString("sname"));
stu.setSname_pinyin(rs.getString("sname_pinyin"));
stu.setAge(rs.getInt("age"));
stu.setRemartk(rs.getString("remark"));
stuList.add(stu);
}
return stuList;
}
});
}
/**
* 专门写一个方法用来拼接查询语句的统计满足条件的总行数
* @param sql 满足条件的sql
* @return
*/
public String getCountSql(String sql) {
return "select count(*) from ("+sql+") t1";
}
/**
* 专门写一个方法用来存储拼接分页的sql
* @param sql 查询指定页码并满足条件的sql语句
* @param pageBaen 助手类
* @return
*/
public String getPageSql(String sql,PageBean pageBean) {
return sql+ "limit "+pageBean.getStartsIndex()+","+pageBean.getRows()+"";
}
}