用list完成分页+排序+条件查询
因为对Mybatis的拦截器了解不深,自己又想写一个类似pageHelper的分页插件,最后决定用很笨拙的方式实现分页+排序+条件查询的功能。
代码如下:
package com.l712.persistent.common; import com.github.pagehelper.PageHelper; import com.l712.pojo.common.PageBean; import com.l712.pojo.common.PageQuery; import com.l712.utils.common.CommonStringUtils; import com.l712.utils.common.SpringUtils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import org.springframework.util.comparator.ComparableComparator; import javax.validation.constraints.NotNull; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; /** * * @author l12 * @T 查询的Pojo */ @Component @NoArgsConstructor @Data public class MyBatisSimplePage<T> { @Value("${method:list}") private String methodName; @NotNull private Method method; @SuppressWarnings("unchecked") public PageBean<T> pageList(Class mapper, Integer pageSize, Integer currentPage, PageQuery pageQuery) { PageBean<T> pageBean = new PageBean<T>(); try { Object o = SpringUtils.getBean(mapper); method = mapper.getMethod(methodName); ArrayList<T> allResults = (ArrayList<T>)method.invoke(o); if(allResults != null && allResults.size()>0){ setPageBean(pageSize, currentPage, pageBean, allResults); List<String> sorts = pageQuery.getSorts(); if(sorts!=null && sorts.size()>0){ for (final String sort:sorts) { Collections.sort(pageBean.getResults(), new Comparator<T>() { @Override public int compare(T t1, T t2) { try { String o1 = t1.getClass().getDeclaredMethod("get"+ CommonStringUtils.toUpperFirstChar(sort)).invoke(t1)+""; String o2 = t2.getClass().getDeclaredMethod("get"+ CommonStringUtils.toUpperFirstChar(sort)).invoke(t2)+""; return o1.compareTo(o2); } catch (Exception e) { e.printStackTrace(); } return 0; } }); } } } return pageBean; } catch (Exception e) { e.printStackTrace(); return null; } } private void setPageBean(Integer pageSize, Integer currentPage, PageBean<T> pageBean, List<T> allResults) { pageBean.setPageSize(pageSize); pageBean.setCurrentPage(currentPage); pageBean.setTotalNum(allResults.size()); pageBean.setTotalPage((pageBean.getTotalNum() + pageSize - 1) / pageSize); if(pageSize > allResults.size()){ pageSize = allResults.size(); }if(currentPage*pageSize > pageBean.getTotalNum()){ pageBean.setResults(allResults.subList((currentPage-1)*pageSize,pageBean.getTotalNum())); }else{ pageBean.setResults(allResults.subList((currentPage-1)*pageSize,currentPage*pageSize)); } } }
条件查询还没写,先睡个午觉,写完补充。TODO