以下是一个分页查询基类的Java实现:

public abstract class PagingQuery<T> {
    private int pageSize;
    private int currentPage;
    private int totalCount;
    private List<T> result;

    public PagingQuery(int pageSize, int currentPage) {
        this.pageSize = pageSize;
        this.currentPage = currentPage;
    }

    public abstract List<T> query();

    public List<T> getResult() {
        if (result == null) {
            result = query();
        }
        return result;
    }

    public int getTotalCount() {
        if (result == null) {
            result = query();
        }
        return totalCount;
    }

    public int getPageCount() {
        int pageCount = (totalCount + pageSize - 1) / pageSize;
        return pageCount;
    }

    public int getPageSize() {
        return pageSize;
    }

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

    public int getCurrentPage() {
        return currentPage;
    }

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

    public void setResult(List<T> result) {
        this.result = result;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
}

使用时,需要继承这个基类并实现query方法来完成具体数据查询,例如:

public class UserQuery extends PagingQuery<User> {
    private String name;

    public UserQuery(int pageSize, int currentPage, String name) {
        super(pageSize, currentPage);
        this.name = name;
    }

    @Override
    public List<User> query() {
        //根据条件查询用户列表
        List<User> userList = userService.findByName(name);

        //设置总记录数
        setTotalCount(userList.size());

        //分页处理
        int fromIndex = (getCurrentPage() - 1) * getPageSize();
        int toIndex = Math.min(fromIndex + getPageSize(), getTotalCount());
        setResult(userList.subList(fromIndex, toIndex));

        return getResult();
    }
}

在实际使用中,可以根据具体的查询需求来扩展这个基类,例如支持按照多个条件查询、排序等功能

用java写一个分页查询基类

原文地址: https://www.cveoy.top/t/topic/cps7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录