【发布时间】:2021-05-26 00:41:57
【问题描述】:
我的 Spring 项目中有一个 Question 实体,它作为响应发送。问题实体与 User 实体具有 @ManyToOne 关系。
问题类
@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;
}
}
用户类
@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 中的 user 对象。整个用户对象作为响应发送。我只想返回 userId 而不是 user 对象。我怎样才能实现它?
【问题讨论】:
标签: java spring-boot hibernate spring-mvc spring-data-jpa