[英]How to send id instead of whole object in Spring MVC??? (Hibernate/Spring-Data-JPA)
I have one Question entity in my Spring project, which is being sent as a response.我的 Spring 项目中有一个 Question 实体,它作为响应发送。 Question entity has @ManyToOne relationship with User entity.
问题实体与用户实体具有@ManyToOne关系。
Question class问题 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;
}
}
User class用户 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;
}
}
I am sending a response in a JSON format.我正在发送 JSON 格式的响应。 Below is the example of my response for a single question.
以下是我对单个问题的回答示例。
{
"questionId": 1,
"question": "What is java?",
"user": {
"userId": 1,
"userName": "JeffHardy"
},
"answerList": [],
}
Just notice the user object in JSON.请注意 JSON 中的用户object。 Whole user object is being sent as a response.
整个用户 object 作为响应发送。 I just want to return userId instead of user object.
我只想返回userId而不是用户object。 How can I achieve it?
我怎样才能实现它?
You can ignore the fields with @JsonIgnoreProperties(value = { "fieldName" })
annotation on class level.您可以忽略 class 级别上带有
@JsonIgnoreProperties(value = { "fieldName" })
注释的字段。 for example:例如:
@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;
}
}
But I suggest to create customized classes for response jsons.但我建议为响应 jsons 创建自定义类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.