在春季数据JPA

时间:2018-07-16 03:16:22

标签: java spring spring-data-jpa spring-data-rest

@RestController
@Transactional
public class ApiController {

    @Autowired
    CategoryService categoryService;

    @SuppressWarnings("deprecation")
    @RequestMapping(value="/api/category/page", method=RequestMethod.GET)
    public Page<Category> getCategoryList() {
        return categoryService.findAll(new PageRequest(0, 10));
    }

}

我想检索要在angularjs中使用的Page,该页面什么也不返回:{}。我getContent ()仍可应要求提供数据:

 [{"cid": 1, "cname": "Tien Hiep", "cmetaTitle": "tien-hiep", 
 "createDate": "May 6, 2018 1:04:58 PM "," createBy ":" Admin "," 
 modifiedDate ":" May 28, 2018 11:09:57 AM "," modifiedBy ":" Admin 
 "," cstatus " ..]

如果我想返回如下页面类型:

    {
        "content":[
            {"cid": 1, "cname": "Tien Hiep", "cmetaTitle": "tien-hiep", "createDate": "May 6, 018 1:04:58 PM "," createBy ":" Admin "," modifiedDate ":" May 28, 2018 11:09:57 AM "," modifiedBy ":" Admin "," cstatus "}, 
            ...
        ],
        "last":false,
        "totalElements":10,
        "totalPages":4,
        "size":10,
        "number":0,
        "sort":null,
        "first":true,
    }

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

如果您添加具有页面限制和偏移量的PageRequest,则JPA将以Page而不是List的形式返回响应。因此,您必须先使用.getContent()将Page转换为List,然后再将其发送到application。这样该应用程序将可以正常运行。

PageRequest pageable= createPageRequest(page,size,sortBy,sortField); /** method to return PageRequest */
Page<TestData> pageList = testDataRepository.findAll(pageable);
List<TestData> testDataList = pageList.getContent();

将返回类型更改为List并添加@Produces(“ application / json”),以便API将数据作为json返回。

如果使用maven,请添加jax-rs或jersey依赖项