JPA使用原生sql实现分页

1、controller层

@GetMapping("/get/myPage")
public JSONObject getAllByMyPage(HttpServletRequest request, HttpServletResponse response, @RequestParam("page") int page, @RequestParam("size") int size){
    PageUtil pageUtil = studentService.findAllStudentByMypage(page, size);//获取数据
    JSONObject jsonObject = (JSONObject) JSON.toJSON(pageUtil);//转为json
    return jsonObject;
}

2、service层

protected EntityManager em;

public PageUtil findAllStudentByMypage(int page, int size){

	/*分页查询数据*/
	Query query = em.createNativeQuery("SELECT * FROM student s LIMIT " + page*size + "," + size);
	List<Student> studentList = query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();//转为Map
	
	/*查询总共的数据条目*/
	query = em.createNativeQuery("SELECT COUNT(*) FROM student");
	Object object = query.getResultList().get(0);
	int totalElements = Integer.parseInt(object.toString());
	
	/*构建自定义Page对象*/
	PageUtil pageUtil = new PageUtil(size, page, totalElements);
	pageUtil.setNumberOfElements(studentList.size());
	pageUtil.setContent(studentList);
	
	return pageUtil;
}

3、json数据

{
    "number": 0,
    "last": false,
    "numberOfElements": 2,
    "size": 2,
    "totalPages": 3,
    "content": [
        {
            "id_card": "41524134",//数据库字段名
            "name": "王宸昊",
            "school_name": "北京科技大学",
            "id": "1",
            "age": 21
        },
        {
            "id_card": "41524133",
            "name": "张三",
            "school_name": "北京大学",
            "id": "2",
            "age": 23
        }
    ],
    "first": true,
    "totalElements": 5
}

从数据库查出的数据的属性是按照数据库中存储的key来进行转换的,所以这里的key是数据库中的字段,可以从query 的 resultList拿出每一条数据再转为Student实体

你可能感兴趣的:(jpa,jpa)