REST-使用Spring MVC返回创建的对象 [英] REST - Returning Created Object with Spring MVC

查看:111
本文介绍了REST-使用Spring MVC返回创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个REST调用,可以接受一个JSON对象,可以说是一个人.创建此对象(已验证并保存到数据库)后,需要返回新创建的JSON对象.

I have a REST call that accepts a JSON object, lets say, a person. After I create this object (validated and saved to the database), I need to return the newly created JSON Object.

我认为标准做法是返回201 Accepted而不是立即返回对象.但是我的应用程序立即需要新创建的对象.

I think the standard practice is to return 201 Accepted instead of returning the object immediately. But my application needs the newly created object immediately.

我有一个控制器方法,该方法接受一个POST调用,调用一个服务类,该服务类又调用一个使用Hibernate创建对象的DAO.一旦将其保存到数据库中,我将调用另一个控制器方法,该方法将获取人员的ID并返回Object.

I have a controller methods that takes a POST call, calls a service class, which in turn calls a DAO that uses Hibernate to create the object. Once it's saved to the database, I am calling another controller method that takes the ID of the person and returns the Object.

我的问题是,这是更好的方法吗?那就是调用另一个Controller方法来获取新创建的对象.否则POST调用本身应返回Object.

My question, is this the better approach? That is calling another Controller method to get the newly created object. Or the POST call itself should return the Object.

主要问题是: 调用另一种方法需要往返,我想这太过分了. (服务-> DAO->休眠->数据库).相反,我认为在将对象保存在同一调用中后(应该从处理POST的方法中),应该立即从数据库中获取该对象.

The main question is: Calling another method takes a round trip and I guess it's an overkill. (Service->DAO->Hibernate->Database). Instead I think I should get the Object from the database immediately after it's saved in the same call (from the method that handled POST).

这里的架构标准是什么?

What is the architecture standard here?

推荐答案

尝试使用ResponseEntity,它返回HTTP状态以及所需的对象.

Try using ResponseEntity which returns HTTP status along with the object you need.

示例代码为(这是我返回客户对象的代码,根据您的需要进行更改):

Sample code is (this was my code where I am returning Customer object, change it as per your needs) :

// imports (for your reference)
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

// spring controller method
@RequestMapping(value = "getcust/{custid}", method = RequestMethod.GET, produces={"application/json"})
public ResponseEntity<Customer> getToken(@PathVariable("custid") final String custid, HttpServletRequest request) {

    customer = service.getCustById(custid);

    return new ResponseEntity<Customer>(customer, HttpStatus.OK);
}

阅读此文档以了解更多的.那里提供了一些示例代码.

Read this documentation to know more. Some sample code has been provided there.

这篇关于REST-使用Spring MVC返回创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆