从提供的网址/store/{storeId}/customers/{customerId}/accounts/{accountId}
中,
显然store has customers
和那些customers have accounts
。
以下方法包括额外的数据库调用,用于按ID验证商店和按ID验证顾客,但这将是适当的方法,因为如果我们在STORE和CUSTOMER表上使用带有联接的查询,那么您可能无法准确判断给定的storeId或customerId不正确/不在数据库中。
如果您逐步进行操作,则可以显示相应的错误消息,
如果storeId不正确-There exists no store with given storeId: XYZ
如果customerId不正确-There exists no customer with customerID: XYZ
由于您提到您正在使用Spring Boot,因此您的代码应如下所示:
@RequestMapping(value = "/store/{storeId}/customers/{customerId}/accounts",method = RequestMethod.POST)
public ResponseEntity<Account> persistAccount(@RequestBody Account account,@PathVariable("storeId") Integer storeId,@PathVariable("customerId") Integer customerId) {
// Assuming you have some service class @Autowired that will query store by ID.
// Assuming you have classes like Store,Customer,Account defined
Store store = service.getStoreById(storeId);
if(store==null){
//Throw your exception / Use some Exception handling mechanism like @ExceptionHandler etc.
//Along with proper Http Status code.
//Message will be something like: *There exists no store with given storeId: XYZ*
}
Customer customer = service.getAccountById(storeId,customerId);
if(customer==null){
//Throw your exception with proper message.
//Message will be something like: *There exists no store with given customerID: XYZ*
}
// Assuming you already have some code to save account info in database.
// for convenience I am naming it as saveAccountAgainstStoreAndCustomer
Account account = service.saveAccountAgainstStoreAndCustomer(storeId,customerId,account);
ResponseEntity<Account> responseEntity = new ResponseEntity<Account>(account,HttpStatus.CREATED);
}
以上代码段只是代码外观的骨架,通过遵循一些良好的编码惯例,您可以以比上面给出的更好的方式来对其进行结构化。
希望对您有帮助。
本文链接:https://www.f2er.com/3092259.html