[英]How to send id instead of whole object in Spring MVC??? (Hibernate/Spring-Data-JPA)
我的 Spring 项目中有一个 Question 实体,它作为响应发送。 问题实体与用户实体具有@ManyToOne关系。
问题 class
@Entity
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int questionId;
@Column
private String question;
@ManyToOne
private User user;
@OneToMany
@JoinColumn(name = "question_id")
private List<Answer> answerList;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Answer> getAnswerList() {
return answerList;
}
public void setAnswerList(List<Answer> answerList) {
this.answerList = answerList;
}
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
}
用户 class
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
我正在发送 JSON 格式的响应。 以下是我对单个问题的回答示例。
{
"questionId": 1,
"question": "What is java?",
"user": {
"userId": 1,
"userName": "JeffHardy"
},
"answerList": [],
}
请注意 JSON 中的用户object。 整个用户 object 作为响应发送。 我只想返回userId而不是用户object。 我怎样才能实现它?
您可以忽略 class 级别上带有@JsonIgnoreProperties(value = { "fieldName" })
注释的字段。 例如:
@Entity
@JsonIgnoreProperties(value = { "userName" })
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
但我建议为响应 jsons 创建自定义类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.