如何在REST中处理不同的响应?

时间:2019-06-07 07:55:49

标签: json hibernate rest spring-mvc

我有2个实体。但是我的回复类型与实体不符。

@Entity
@Table(name="customer")
public class Customer {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

private String firstname;
private String lastname;
private boolean available;

@OneToMany(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinColumn(name="customer_id")
private List<Product> products;


public Customer() {
    // TODO Auto-generated constructor stub
}


public Customer(String firstname, String lastname, boolean available) {
    super();
    this.firstname = firstname;
    this.lastname = lastname;
    this.available = available;
}


public String getFirstname() {
    return firstname;
}


public void setFirstname(String firstname) {
    this.firstname = firstname;
}


public String getLastname() {
    return lastname;
}


public void setLastname(String lastname) {
    this.lastname = lastname;
}


public boolean isAvailable() {
    return available;
}

public void setAvailable(boolean available) {
    this.available = available;
}

public List<Product> getProducts() {
    return products;
}

public void addProduct(Product product) {
if(products==null)
    products=new LinkedList<Product>();
    products.add(product);
}


@Override
public String toString() {
    return "Customer [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname
            + ", available=" + available + "]";
}

}

[GET]本地主机:8080 / myapp / customers / {id} 在这里,我想获取客户的所有数据(id,名字,姓氏,可用的产品)

{
"id" : 1,
"name" : "John",
"lastname" : "Doe",
"available" : false
"products" : {...}
}

[GET]本地主机:8080 / myapp / customers 但在这里我想带给客户一些数据(仅id,firstname,lastname)

[{
"id" : 1,
"name" : "John",
"lastname" : "Doe",
},
{
"id" : 2,
"name" : "Alex",
"lastname" : "Adams",
}]

我应该为每个响应创建新的类吗?或在控制器中编辑json数据?

2 个答案:

答案 0 :(得分:0)

您应该隔离:

  • 实体用于数据库操作

  • DTO用于与其他服务通信

因此,根据您的情况,我建议您创建DTO来处理这种情况。请注意,有许多库可以简化DTO和实体之间的转换,例如ModelMapper。

答案 1 :(得分:0)

您可以使用单个Response DTO。 示例:

此响应类型可以为import React, { Component } from "react"; import Search from "./components/Search"; import RecipesList from "./components/RecipesList"; import Recipe from "./components/Recipe"; import Constansts from "./components/constants"; import axios from "axios"; class App extends Component { state = { recipesList: [], isLoading: false, itemId: "", recipe: "", ingredients: "" }; getQuery = async query => { const { key } = Constansts; const URL = `https://www.food2fork.com/api/search?key=${key}&q=${query}`; if (query) { console.log(); this.renderLoader(); try { var res = await axios(URL); this.setState({ recipesList: res.data.recipes, isLoading: true }); console.log(this.state.isLoading); if (this.state.recipesList.length) { this.setState({ isLoading: false }); console.log(this.state.isLoading); this.removeLoader(); } } catch (error) { console.log(error); } } }; renderLoader() { const recipesRef = this.refs.recipesRef; const mark = `<div class="loader"> <svg viewBox="0 0 20 20"> <path d="M19.315 10h-2.372v-0.205c-0.108-4.434-3.724-7.996-8.169-7.996-4.515 0-8.174 3.672-8.174 8.201s3.659 8.199 8.174 8.199c1.898 0 3.645-0.65 5.033-1.738l-1.406-1.504c-1.016 0.748-2.27 1.193-3.627 1.193-3.386 0-6.131-2.754-6.131-6.15s2.745-6.15 6.131-6.15c3.317 0 6.018 2.643 6.125 5.945v0.205h-2.672l3.494 3.894 3.594-3.894z"></path> </svg> </div>`; recipesRef.insertAdjacentHTML("afterbegin", mark); } removeLoader() { const recipesRef = this.refs.recipesRef; recipesRef.removeChild(recipesRef.childNodes[0]); } render() { const { isLoading, recipesList, ingredients, recipe } = this.state; return ( <div className="App"> <div className="wrapper"> <Search query={this.getQuery} /> <div className="recipesWrapper" ref="recipesRef"> <RecipesList isLoading={isLoading} recipesList={recipesList} /> </div> </div> </div> ); } } export default App;

CustomerDTO

以下API的响应类型可以为[GET] localhost:8080/myapp/customers/{id}

List<CustomerDTO>