使用Java封装的分页工具类,附源码,带注释,复制粘贴就能用

项目结构

项目结构

功能展示

分页

Page

package com.laner.util;
import java.util.List;

public class Page {
    private int pageSize;       //每页条数
    private int pageCount;      //总页数
    private int currentPage;    //当前页
    private int recordCount;    //记录总数
    private List<Object> list;  //页面数据
    private String tableName;   //分页表名

    // 默认每页数据数量
    public Page(int currentPage, String tableName) {
    	//pageSize默认为5
    	this(5, currentPage, tableName)
    }

    // 自定义每页数据数量
    public Page(int pageSize, int currentPage, String tableName) {
        //每页数量 -> 表名 -> 表中记录总数 -> 总页数 -> 当前页(上下限判断) -> 页数据
        this.pageSize = pageSize; 
        this.tableName = tableName;
        this.recordCount = PageData.setRecordCount(tableName);
        this.pageCount = (int) Math.ceil((recordCount + 0.0) / pageSize);

        if (currentPage < 1) currentPage = 1;
        if (currentPage > pageCount) currentPage = pageCount;
        this.currentPage = currentPage;

        this.list = PageData.setPageList(this, tableName);
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getRecordCount() {
        return recordCount;
    }

    public void setRecordCount(int recordCount) {
        this.recordCount = recordCount;
    }

    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }
}

PageDate

package com.laner.util;

import java.util.ArrayList;
import java.util.List;

public class PageData {
    public static List setPageList(Page page, String tableName){
        List list = new ArrayList();
        try {
            Class clazz = Class.forName("com.laner.vo." + tableName);
            int start = (page.getCurrentPage() - 1) * page.getPageSize();
            int size = page.getPageSize();
            String sql = "select * from " + tableName + " limit " + start + ", " + size;

            list = DBExecute.executeQuery(clazz, sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static int setRecordCount(String tableName){
        return Math.toIntExact(DBExecute.executeQuery("select count(*) from " + tableName));
    }
}


DBConnection

package com.laner.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Properties;

public class DBConnection {
    private static Connection conn;

    static {
        try {
            Properties properties = new Properties();
            //Web项目在Tomcat下查找properties文件
            //String propertiesPath = Objects.requireNonNull(DBConnection.class.getClassLoader().getResource("myPro.properties")).getPath().replace("%20"," ");
            //Java项目查找properties文件
            String propertiesPath = "src/com/laner/myPro.properties";
            properties.load(new FileInputStream(propertiesPath));

            String dbClassName = (String)properties.get("DBClassName");
            String dbUrl = (String)properties.get("DBURL");
            String dbUsername = (String)properties.get("DBUsername");
            String dbPassword = (String)properties.get("DBPassword");

            Class.forName(dbClassName);
            conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() {
        return conn;
    }
}

DBExecute

package com.laner.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

public class DBExecute {
    //万能查询方法,返回Map<Integer, Object>
    // Integer只是计数,Object为数据
    public static Map<Integer, Object> executeQuery(String sql, Object... args){
        Map<Integer, Object> map = new HashMap();
        int key = 0;
        try(PreparedStatement ps = DBConnection.getConn().prepareStatement(sql)) {
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            ResultSet rs = ps.executeQuery();

            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (rs.next()){
                for (int i = 1; i <= columnCount; i++) {
                    map.put(key++, rs.getObject(i));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return map;
    }

    //查询方法,返回相应对象集合,受限很多,但是新手阶段的很常用,对于理解反射和数据库封装非常有帮助
    // 适用于任何表: select * from / select u_id,u_name,... from
    // 不适用于返回值与类属性无关的sql: 例如:select count(*)/sun(*)/min(*)等
    // 不适用于多表查询的sql: 例如:select id, name from a, b等
    public static <T> List<T> executeQuery(Class<T> tClass, String sql, Object... args){
        List<T> list = new ArrayList<>();

        try(PreparedStatement ps = DBConnection.getConn().prepareStatement(sql)) {
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();

            Constructor<T> constructor = tClass.getConstructor();
            while (rs.next()){
                T t = constructor.newInstance();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String columnName = rsmd.getColumnName(i);

                    Field field = tClass.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(t, rs.getObject(columnName));
                }
                list.add(t);
            }
        } catch (SQLException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        return list;
    }

    //万能修改方法,返回受影响行数int
    public static int executeUpdate(String sql, Object... args){
        try(PreparedStatement ps = DBConnection.getConn().prepareStatement(sql)) {
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}

myPro.propertise

DBClassName = com.mysql.cj.jdbc.Driver
DBURL = jdbc:mysql://localhost:3306/mydatabase
DBUsername = root
DBPassword = root

总结

这两天又优化了一下代码,然后消除了一点代码冗余
复制粘贴直接用~
主页里免费下载完整的Web分页项目Demo,点进去就能看见资源
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值