拦截器实现分页

<div class="iteye-blog-content-contain" style="font-size: 14px"></div>

 一、配置mybastis插件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <plugins>
        <plugin interceptor="com.zhiyi.common.mybatis.SearchInterceptor" />
    </plugins>

    <mappers>
    </mappers>
</configuration>

二、mybatis连接器实现

import com.zhiyi.common.dto.PageSearchDto;
import org.apache.ibatis.executor.statement.PreparedStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Properties;


public class SearchInterceptor implements Interceptor {


    public Object intercept(Invocation invocation) throws Throwable {
        return invocation.proceed();
    }

    public Object plugin(Object target) {
        Type[] interfaces = target.getClass().getGenericInterfaces();
        for (Type i : interfaces) {
            if (i.equals(StatementHandler.class)) {
                StatementHandler statementHandler = (StatementHandler) target;
                Field statementField = ReflectionUtils.findField(statementHandler.getClass(), "delegate");
                ReflectionUtils.makeAccessible(statementField);
                Object fieldInstance = ReflectionUtils.getField(statementField, statementHandler);

                Field mappedStatementField = ReflectionUtils.findField(fieldInstance.getClass(), "mappedStatement");
                ReflectionUtils.makeAccessible(mappedStatementField);

                MappedStatement mappedStatement = (MappedStatement) ReflectionUtils.getField(mappedStatementField, fieldInstance);

                if (mappedStatement.getSqlCommandType() == SqlCommandType.SELECT && fieldInstance.getClass().equals(PreparedStatementHandler.class)) {
                    PreparedStatementHandler preparedStatementHandler = (PreparedStatementHandler) fieldInstance;
                    BoundSql boundSql = preparedStatementHandler.getBoundSql();
                    if (boundSql.getParameterObject() != null &&
                            (boundSql.getParameterObject().getClass().getSuperclass().equals(PageSearchDto.class))
                            ) {
                        String additionalSql = null;
                        if (boundSql.getParameterObject().getClass().getSuperclass().equals(PageSearchDto.class)) {
                            PageSearchDto searchDto = (PageSearchDto) boundSql.getParameterObject();
                            if (searchDto.getTotalSize() == -1) {
                                return target;
                            }
                            additionalSql = searchDto.getPageableAndSortableSqlString();
                        }
                        String originalSql = boundSql.getSql();
                        Field sqlField = ReflectionUtils.findField(BoundSql.class, "sql");
                        ReflectionUtils.makeAccessible(sqlField);
                        ReflectionUtils.setField(sqlField, boundSql, originalSql + additionalSql);
                    }
                    return target;
                }
            }
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }


}

三、通过继承类方式实现

/**
 * mybatis拦截器 对应分页dto
 */
public class PageSearchDto extends SearchDto {

    //每页记录数
    protected int pageSize = 20;

    //当前第几页
    protected int currentPage = 1;

    //总记录数
    protected int totalSize;

    //总页数
    protected int totalPage;

    //排序字段
    protected List<String> sortColumn = new ArrayList<String>();

    protected List<String> sortDirection = new ArrayList<String>();

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    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 List<String> getSortColumn() {
        return sortColumn;
    }

    public void setSortColumn(List<String> sortColumn) {
        this.sortColumn = sortColumn;
    }

    public List<String> getSortDirection() {
        return sortDirection;
    }

    public int getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(int totalSize) {
        this.totalSize = totalSize;
    }

    public void setSortDirection(List<String> sortDirection) {
        this.sortDirection = sortDirection;
    }

    public void addSortCriteria(String property, String direction) {
        getSortColumn().add(property);
        getSortDirection().add(direction);
    }

    protected String getSortableSql() {
        if (getSortColumn().size() == 0) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder(" order by ");
        for (int i = 0; i < sortColumn.size(); i++) {
            stringBuilder.append(sortColumn.get(i)).append(" " + sortDirection.get(i) + ", ");
        }
        return stringBuilder.substring(0, stringBuilder.length() - 2);
    }

    protected String getPageableSql() {
        StringBuilder stringBuilder = new StringBuilder("");
        if (currentPage <= 1 && pageSize != -1) {
            stringBuilder.append("limit ").append("0," + pageSize);
        } else if (currentPage > 1) {
            int start = (currentPage - 1) * pageSize;
            stringBuilder.append("limit ").append(start + "," + pageSize);
        }

        return stringBuilder.toString();
    }

    public void clearSort() {
        if (null != sortColumn) {
            sortColumn.clear();
        }
        if (null != sortDirection) {
            sortDirection.clear();
        }
    }

    public void resetPagination(int currentPage, int pageSize, String property, String direction) {
        this.clearSort();
        this.setCurrentPage(currentPage);
        this.setPageSize(pageSize);
        if (StringUtils.isNotBlank(property) || StringUtils.isNotBlank(direction)) {
            this.addSortCriteria(property, direction);
        }
    }

    public String getPageableAndSortableSqlString() {
        return getSortableSql() + " " + getPageableSql();
    }

    public int calTotalPage(int totalSize) {
        this.totalSize = totalSize;
        int page = totalSize / pageSize;
        this.totalPage = (totalSize % pageSize) == 0 ? page : page + 1;
        return totalPage;
    }

    //设置不分页
    public Object disablePaging() {
        this.setTotalSize(-1);
        return this;
    }

    public Object openPaging() {
        this.setTotalSize(0);
        return this;
    }
}
扫描二维码关注公众号,回复: 609374 查看本文章

四、使用demo

 List<AdminSection> adminSections = adminSectionMapper.search(sectionSearchDto);
        List<AdminSectionDto> adminSectionDtos = PropertiesUtils.copyList(AdminSectionDto.class, adminSections);
        return new PageSearchResultDto<>(this.count(sectionSearchDto), adminSectionDtos);

猜你喜欢

转载自noudisan.iteye.com/blog/2311774