简体   繁体   中英

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. Question entity has @ManyToOne relationship with User entity.

Question 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

@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. 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. Whole user object is being sent as a response. I just want to return userId instead of user object. How can I achieve it?

You can ignore the fields with @JsonIgnoreProperties(value = { "fieldName" }) annotation on class level. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM