Spring data JPA先排序再分页。

//工具类,增删改查等等
package
com.yunqing.service.impl; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.transaction.annotation.Transactional; import org.springside.modules.persistence.DynamicSpecifications; import org.springside.modules.persistence.SearchFilter; public class RootServiceImpl<T> { @Autowired PagingAndSortingRepository<T, String> pasr; @Autowired JpaSpecificationExecutor<T> jpas; /** * 根据条件查询 * @param paramMap * @param page * @param rows * @param clazz * @return */ @Transactional(readOnly=true) public Page<T> findAllByParam(Map<String, Object> paramMap, int page,int rows,Class<T> clazz) { Map<String, SearchFilter> filters = SearchFilter.parse(paramMap); Specification<T> spec = DynamicSpecifications.bySearchFilter(filters.values(),clazz); Pageable pageable = new PageRequest(page, rows); Page<T> resultPage = jpas.findAll(spec,pageable); return resultPage; } /** * 根据ID查询 * @param id * @return */ //@Transactional(readOnly=true) public T findEntityById(String id){ T t=pasr.findOne(id); return t; } /** * 查询全部 * @return */ @Transactional(readOnly=true) public Iterable<T> findAllEntity(){ Iterable<T> list=pasr.findAll(); return list; } /** * 删除 * @param id */ @Transactional public void deleteEntityById(String id){ pasr.delete(id); } /** * 删除 * @param t */ @Transactional public void deleteEntity(T t){ pasr.delete(t); } /** * 删除多个 * @param ids */ @Transactional public void deleteEntity(Iterable<T> iterable){ pasr.delete(iterable); } /** * 保存 * @param t */ @Transactional public void save(T t){ pasr.save(t); } /** * 保存 * @param tList */ @Transactional public void save(Iterable<T> tList){ pasr.save(tList); } /** * 删除多个/单个 * <b>deleteEntity</b> * <p><b>详细说明:</b></p> * *@param ids */ @Transactional public void deleteEntity(String ids){ if(ids!=null&&!"".equals(ids)){ if(ids.contains(":")){ String[] idArr = ids.split(":"); for(String id : idArr){ deleteEntityById(id); } }else{ deleteEntityById(ids); } } } @Transactional public Page<T> findAllByParam(Map<String, Object> paramMap, int page,int rows,Class<T> clazz,Sort sort) { Map<String, SearchFilter> filters = SearchFilter.parse(paramMap); Specification<T> spec = DynamicSpecifications.bySearchFilter(filters.values(),clazz); Pageable pageable = new PageRequest(page, rows,sort); Page<T> resultPage = jpas.findAll(spec,pageable); return resultPage; } }

service层

package com.yunqing.service.impl;

import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.tideway.live.vo.Student;
import com.tideway.utils.FileUtil;

@Service("/studentService")
public class StudentServiceImpl extends RootServiceImpl<Student>{
//查询所有的学生,先排序后查询!!!!!!!!!!!!sort是排序条件参数,在controller层给参数赋值
    public Page<Student> queryStudentList(Map<String, Object> paramMap, int page, int rows,Sort sort) {
        // TODO Auto-generated method stub
        //Page<Student> esultPage = findAllByParam(paramMap, page, rows,Student.class);    
        Page<Student> esultPage=findAllByParam(paramMap, page, rows, Student.class,sort);
        return esultPage;
    }
}

controller层

package com.yunqing.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.tideway.live.service.impl.StudentServiceImpl;
import com.tideway.live.vo.Student;
import com.tideway.utils.FileUtil;

@Controller
@RequestMapping("/student")
public class StudentController extends BaseController{
    
    @InitBinder("student")    
    public void initBinder(WebDataBinder binder) {    
            binder.setFieldDefaultPrefix("student.");    
    }
    
    @Autowired
    private StudentServiceImpl studentService;
    
    /**
     * 获取学员列表
     * @param request
     * @param response
     * @param student
     */
    @RequestMapping("/queryStudentList")
    public void queryStudentList(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("student") Student student){
        Map<String, Object> paramMap = new HashedMap<String, Object>();
        if(student.getName()!=null&&!"".equals(student.getName())){
            paramMap.put("LIKE_name", student.getName());
        }
        //直接创建sort对象,通过排序方法和属性名
        Sort sort=new Sort(Direction.DESC,"createTime");//createTime是学生的录入时间,这样展示的时候就会按录入时间先排序再分页展示。
        //Page<Student> page  = studentService.queryStudentList(paramMap,this.getPage(request), this.getRows(request));
        Page<Student> page  = studentService.queryStudentList(paramMap, this.getPage(request), this.getRows(request),sort);
        List<Student> list = page.getContent();
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("total",page.getTotalElements());
        json.put("rows",list);
        returnJson(response,json);
    }
}

 也可以在service层搞定,还可以实现先多条件排序在分页。

public Page<SpecialguardInfo> findAllByParam(Map<String, Object> paramMap, int page, int rows) {
        // 先根据状态倒序排列,再根据创建时间倒序排序,再分页。
        List<Order> orders=new ArrayList<Sort.Order>();
        orders.add(new Order(Direction.DESC, "_state"));
        orders.add(new Order(Direction.DESC, "createtime"));
        //Sort sort = new Sort(Sort.Direction.DESC,"createtime");
        Page<SpecialguardInfo> page1=findAllByParam(paramMap, page, rows, SpecialguardInfo.class, new Sort(orders));//注意参数要修改成这样
        return page1;
    }

更多精彩文章欢迎关注公众号“Java之康庄大道”

原文地址:https://www.cnblogs.com/yunqing/p/7245619.html