【问题标题】:How to return collection of entities without pagination? Spring Boot REST如何在没有分页的情况下返回实体集合? Spring Boot REST
【发布时间】:2016-11-08 06:30:12
【问题描述】:

我有一个简单的 Spring Boot 应用程序。我的控制器如下所示:

@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Employee> getAllEmployees() {
    return employeeRepository.findAll();
}

此代码生成此 json:

{
  "_embedded" : {
    "employees" : [ {
      "firstName" : "firstName1",
      "lastName" : "lastName1",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/employees/1"
        },
        "employee" : {
          "href" : "http://localhost:8080/employees/1"
        }
      }
    }, {
      "firstName" : "firstName 1",
      "lastName" : "lastName 1",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/employees/2"
        },
        "employee" : {
          "href" : "http://localhost:8080/employees/2"
        }
      }
    }, {
      "firstName" : "firstName 3",
      "lastName" : "lastName 3",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/employees/4"
        },
        "employee" : {
          "href" : "http://localhost:8080/employees/4"
        }
      },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/employees"
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/employees"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 7,
    "totalPages" : 1,
    "number" : 0
  }
}

但我需要这样的东西:

[
    {
      "firstName" : "firstName1",
       "lastName" : "lastName1",
    },
        {
      "firstName" : "firstName2",
       "lastName" : "lastName2",
    },
]

【问题讨论】:

  • 您可以使用@JsonView 选择您要显示的数据。见coderelief.io/index.php/2015/11/07/…
  • @MarcoA.Hernandez 据我所知,此注释用于选择实体的字段。分页出现在 spring-boot-starter-data-rest 之外。但我不知道,如何禁用它。
  • 您的employeeRepository 已定义为PagingAndSortingRepository。如果您不需要分页,请将其定义为简单的 CrudRepository。如果要控制分页(最大结果等),则必须在请求的 url 中使用参数,例如 localhost:8080/?limit=50

标签: java json spring rest spring-boot


【解决方案1】:

解决方案是移除 spring-boot-starter-data-rest 模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 2019-12-27
    • 2019-11-08
    • 2020-12-23
    • 2016-09-20
    • 2020-10-21
    • 2020-04-24
    • 2021-12-05
    相关资源
    最近更新 更多