【问题标题】:How to send id instead of whole object in Spring MVC??? (Hibernate/Spring-Data-JPA)如何在 Spring MVC 中发送 id 而不是整个对象??? (休眠/Spring-Data-JPA)
【发布时间】: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


    【解决方案1】:

    您可以在类级别忽略带有@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 创建自定义类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2014-08-14
      • 2012-07-30
      相关资源
      最近更新 更多