且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

springmvc+jpa实现分页的两种方式

更新时间:2022-09-26 09:34:47

v1.工具类

springmvc+jpa实现分页的两种方式
public final class QueryTool {
    public static PageRequest buildPageRequest(int pageNumber, int pageSize, String sortType){
        Sort sort = null;
        if("auto".equals(sortType)) {
            sort = new Sort(Direction.DESC, "ctime");
        } else {
            sort = new Sort(Direction.DESC, "ctime");
        }
        
        return new PageRequest(pageNumber, pageSize, sort);
    }
    
    public static <T> Specification<T> buildSpecification(Map<String, Object> searchParams, Class<T> domainClass){
        Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        Specification<T> spec = DynamicSpecifications.bySearchFilter(filters.values(), domainClass);
        return spec;
    }
}
springmvc+jpa实现分页的两种方式

v2.Service类(只给出CommentService)

springmvc+jpa实现分页的两种方式
@Service
public class CommentService {
    @Autowired
    private CommentDao commentDao;
    
    @Transactional
    public void addComment(Comment comment) {
        if(comment == null) return;
        commentDao.save(comment);
    }
    
    @Transactional
    public Page<Comment> findAllComments(String problemId, PageRequest pageable){
        Page<Comment> page = commentDao.findAllCommentsByProblemId(problemId, pageable);
        return page;
    }
}
springmvc+jpa实现分页的两种方式

v3.repository类(problem 和 comment 属于 一对多 的关系)

springmvc+jpa实现分页的两种方式
@Repository
public interface CommentDao extends JpaSpecificationExecutor<Comment>,
    PagingAndSortingRepository<Comment, String> {
    
    @Query("select c from Comment c where c.problem.problemid = ?1")
    public Page<Comment> findAllCommentsByProblemId(String problemId, Pageable pageable);
}
springmvc+jpa实现分页的两种方式

v 4.Controller类

  第一种方式

springmvc+jpa实现分页的两种方式
@Controller
public class ProblemController {
    
    @Autowired
    private ProblemService problemService;
    
    @Autowired
    private CommentService commentService;
    
    @RequestMapping(value="getCurProblemComments")
    @ResponseBody
    public String getCurProblemComments(String problemName, @RequestParam(value = "pn", defaultValue = "1") int pageNumber,
            @RequestParam(value = "ps", defaultValue = "4") int pageSize,
            @RequestParam(value = "sortType", defaultValue = "auto") String sortType){
        JSONObject jsono = new JSONObject();
        try {
            Problem problem = problemService.getProblemByName(problemName);
            if(problem == null){
                problem = problemService.addProblem(problemName);
            }
            PageRequest pageRequest = QueryTool.buildPageRequest(pageNumber, pageSize, sortType);
            //根据题目的id获取所有的评论
            Page<Comment> page = commentService.findAllComments(problem.getProblemid(), pageRequest);
            //对 Comment 这个类中的一些字段进行过滤
            SimplePropertyPreFilter spp = new SimplePropertyPreFilter();
            spp.getExcludes().addAll(Comment.getExcludeString());
            jsono.put("success", true);
            jsono.put("message", JSON.toJSONString(page, spp));
        } catch(Exception e){
            e.printStackTrace();
            jsono.put("success", false);
            jsono.put("message", "inner error.");
        }
        return jsono.toString();
    }
}
springmvc+jpa实现分页的两种方式

  

  第二种方式,(懒了,有些内容是放在servic中的。)

  通过JpaSpecificationExecutor<T> 的Page<T> findAll(Specification<T> spec, Pageable pageable); 方法(按照指定的规格条件)实现分页查询。

springmvc+jpa实现分页的两种方式
public String getCurProblemComments(@RequestParam(value = "pn", defaultValue = "1") int pageNumber,
        @RequestParam(value = "ps", defaultValue = "2") int pageSize,
        @RequestParam(value = "sortType", defaultValue = "auto") String sortType, ServletRequest request) {
    Map<String, Object> searchParams = new HashMap<String, Object>();
    searchParams = Servlets.getParametersStartingWith(request, "search_");
    System.out.println(EncodeUtils.toUTF8((String)searchParams.get("LIKE_name")));
    PageRequest pageRequest = QueryTool.buildPageRequest(pageNumber, pageSize, sortType);
    searchParams.put(Operator.EQ + "_dr", "0");//逻辑删除中,字段dr=0表示这条数据没有删除
    Specification<Comment> spec = QueryTool.buildSpecification(searchParams, Comment.class);
    Page<Comment> page = commentDao.findAll(spec, pageRequest);
    return JSON.toJSONString(page);
}
springmvc+jpa实现分页的两种方式

  其中,Specification中的一些比较操作org.springside.modules.persistence.SearchFilter.Operator这个类中找到,如下:

public static enum Operator {
   EQ, LIKE, GT, LT, GTE, LTE;
}

  前台传递过来的参数名称中可以包含 Operator 中的一些操作, 比如参数名称是: search_LIKE_name (search表示要查询时比较, LIKE是比较的操作, name是表的字段名)

v5.java简单实现分页

springmvc+jpa实现分页的两种方式

 

分页面板类(MyPagePanel.java)

springmvc+jpa实现分页的两种方式 View Code

MyMessage.class

springmvc+jpa实现分页的两种方式 View Code

MyPage.class

springmvc+jpa实现分页的两种方式 View Code

  实现思路:

1. 首先看一下后台的json数据的格式(其中message的值是spring Data JPA分页查询结果的json)

{"success":true,"message":{"content":[{"ccontent":"hjz 2016-38-11 15:38:21*****宋体|12|0-0-0| *****0$$$$$70#####","commentid":"8ae45d92549da2a801549ec092ce001f"},{"ccontent":"hjz 2016-38-11 15:38:10*****宋体|12|0-0-0|哇哇 *****2$$$$$55#####","commentid":"8ae45d92549da2a801549ec068c7001e"}],"first":true,"last":false,"number":0,"numberOfElements":2,"size":2,"sort":{},"totalElements":8,"totalPages":4}}

 

2. 将“message”对应的值转换成MyPage对象,因为MyPage中有一个List<MyMessage>,如果属性中含有复杂的类型,当其中属性有类似List , Map ,ArrayList、自定义的类型,如List<MyMessage> content, 普通的转换会报错:java.lang.ClassCastException: net.sf.ezmorph.bean.MorphDynaBean cannot be cast to XXX,在JSONObject.toBean的时候如果转换的类中有集合,可以先定义Map<String, Class> classMap = new HashMap<String, Class>();在classMap中put你要转换的类中的集合名 。本例中需要将“content”对应的值转换成 MyMessage对象。

springmvc+jpa实现分页的两种方式
//data为后台的json串
JSONObject result = JSONObject.fromObject(data);
if((Boolean) result.get("success")){//分页显示
    JSONObject message = JSONObject.fromObject(result.get("message"));
    Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
    classMap.put("content", MyMessage.class);
    MyPage myPage = (MyPage) JSONObject.toBean(message, MyPage.class, classMap);
    this.updatePage(myPage);
}
springmvc+jpa实现分页的两种方式

3.然后通过分页的信息,简单的实现分页按钮,详情看MyPagePanel.java










本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/5477523.html,如需转载请自行联系原作者