我正在尝试使用spring-boot-starter-data-rest使用Spring Boot构建RESTful API.有一些实体:帐户,交易,类别和用户 - 只是通常的东西.
当我通过默认生成的API 检索http:// localhost:8080/transactions中的对象时,一切顺利,我得到一个包含所有事务的列表作为JSON对象,如下所示:
{
"amount": -4.81,
"date": "2014-06-17T21:18:00.000+0000",
"description": "Pizza",
"_links": {
"self": {
"href": "http://localhost:8080/transactions/5"
},
"category": {
"href": "http://localhost:8080/transactions/5/category"
},
"account": {
"href": "http://localhost:8080/transactions/5/account"
}
}
}
Run Code Online (Sandbox Code Playgroud)
但现在的目标是仅检索该URL下的最新事务,因为我不想序列化整个数据库表.所以我写了一个控制器:
@Controller
public class TransactionController {
private final TransactionRepository transactionRepository;
@Autowired
public TransactionController(TransactionRepository transactionRepository) {
this.transactionRepository = transactionRepository;
}
// return the 5 latest transactions
@RequestMapping(value = "/transactions", method = RequestMethod.GET)
public @ResponseBody List<Transaction> getLastTransactions() {
return transactionRepository.findAll(new PageRequest(0, 5, new Sort(new Sort.Order(Sort.Direction.DESC, "date")))).getContent(); …Run Code Online (Sandbox Code Playgroud) spring spring-mvc spring-data-rest spring-hateoas spring-boot