使用Spring Data REST设置X-Total-Count

时间:2017-09-08 16:58:49

标签: spring rest spring-data-rest

我正在测试Spring Data REST。 我正在关注this tutorial以了解其工作原理。

到目前为止,代码很简单:

@Entity
@SequenceGenerator(name="my_seq", sequenceName="user_id_seq")
@Table(name = "employees")
data class Employee (@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq") val id: Long? = null,
                     val name: String = "defConstructorHell")

当我问GET时,我获得了以下json:

{
  "_embedded" : {
    "employees" : [ {
      "name" : "ciao",
      "_links" : {
        "self" : {
          "href" : "http://localhost:5000/api/employees/1"
        },
        "employee" : {
          "href" : "http://localhost:5000/api/employees/1"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:5000/api/employees{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:5000/api/profile/employees"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

哪个完全没问题,但我使用的是需要标题X-Total-Count的js框架。

你知道是否有办法使用Spring Data REST吗?

1 个答案:

答案 0 :(得分:0)

最后我添加了一个添加请求标头的控制器:

@RepositoryRestController
class EmployeeController @Autowired constructor(val repo: EmployeeRepository) {

    @RequestMapping(method = arrayOf(GET),
            path = arrayOf("employees"))
    @ResponseBody
    fun getEmployees(@RequestParam("_sort", required = false, defaultValue = "id") _sort: String,
                     @RequestParam("_order", required = false, defaultValue = "DESC") _order: String,
                     @RequestParam("_start", required = false, defaultValue = "0") _start: Int,
                     @RequestParam("_end", required = false, defaultValue = "20") _end: Int): ResponseEntity<MutableIterable<Employee>> {
        val pr = PageRequest(_start, 20, Sort.Direction.valueOf(_order), _sort)
        val result = repo.findAll(pr)
        val headers = HttpHeaders()
        headers.add("X-Total-Count", result.count().toString())
        return ResponseEntity(result.content, headers, OK)
    }
}