【问题标题】:Json Pagination not working from PageImplJson Pagination 不能从 PageImpl 工作
【发布时间】:2018-01-29 13:16:16
【问题描述】:

我有这个控制器:

@RequestMapping("/api")
    public ResponseEntity<?> a(Pageable pageable) throws IOException {
        ObjectMapper mapper = new ObjectMapper(  );
        File file = new File( "samplejson.json" );
        JsonNode jsonNode = mapper.readTree( file );
        List<JsonNode> nodes = new ArrayList<>();
        if ( !jsonNode.isArray() )
            nodes.add( jsonNode );
        else 
            for ( JsonNode node : jsonNode )
                nodes.add( node );
        return new ResponseEntity<Object>( new PageImpl( nodes, pageable, nodes.size() ), HttpStatus.OK );
    }

当我邮递它时,它给了我这样的回应:

{
    "content": [
        {
            "id": 1,
            "first_name": "Dode",
            "email": "dcardall0@zimbio.com",
            "gender": "Female",
            "timestamp": "11/12/1981"
        },
        {
            "id": 2,
            "first_name": "Andrus",
            "email": "amcgeever1@jigsy.com",
            "gender": "Male",
            "timestamp": "10/25/1988"
        },
        {
            "id": 3,
            "first_name": "Allyn",
            "email": "afakes2@samsung.com",
            "gender": "Male",
            "timestamp": "9/3/1997"
        },
        {
            "id": 4,
            "first_name": "Merell",
            "email": "mmoreton3@census.gov",
            "gender": "Male",
            "timestamp": "3/7/2009"
        }
    ],
    "last": true,
    "totalElements": 10,
    "totalPages": 1,
    "size": 20,
    "number": 0,
        "sort": [
    {
        "direction": "DESC",
        "property": "id",
        "ignoreCase": false,
        "nullHandling": "NATIVE",
        "descending": true,
        "ascending": false
    }
],
    "first": true,
    "numberOfElements": 10 }

在 URI 中我有这个

http://localhost:8080/api?sort=id, desc

但是分页不起作用。如您所见,响应中的排序方向显示为“DESC”。所以应该是降序吧?但它不起作用。我认为是因为它位于由分页创建的对象内容中。但我不知道如何访问里面的内容。

【问题讨论】:

    标签: java spring spring-boot pagination spring-data


    【解决方案1】:

    为了应用 PageRequest 选项,如排序等,您需要使用 PagingAndSortingRepository(请参阅Spring Paging documentation

    所以排序和获取页面是在存储库逻辑中执行的。见 org.springframework.data.jpa.repository.support.SimpleJpaRepository.readPage

    您也可以阅读本教程:https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-seven-pagination/

    【讨论】:

    • 我知道 PagingAndSortingRepository。但是,我从 jsonfile 中获取数据。它仍然适用吗?我知道使用存储库是我需要在 application.properties 中配置一个 sql 数据库或 h2。但这是来自 jsonfile。是否可以将application.properties中的json文件导入为数据库?
    • 为了使分页和排序与 json 文件一起工作,您需要自己实现逻辑。您可以参考现有的 PagingAndSortingRepository 实现作为示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2017-08-29
    • 2017-11-29
    • 2023-02-03
    • 1970-01-01
    相关资源
    最近更新 更多