我正在测试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吗?
答案 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)
}
}