英文:
Hide ManyToOne field in REST API in Spring Boot
问题
我在服务器上使用Spring Boot创建了一个简单的REST API。我有两个资源:用户(users)和文章(articles)。以下是Article类的代码:
@Entity(name = "article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false)
private String text;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
public User getUser() { // 我需要这个方法。
return user;
}
// 其他所有的setter和getter方法。
}
现在,如果我通过REST API根据文章的ID获取一些文章,响应如下:
{
"id": 5,
"text": "文章的内容...",
"user": {
"id": 1,
"username": "user@email.com",
"password": "$2a$10$CbsH93d8s5NX6Gx/N5zcwemUJ7YXXjRIQAE2InW9zyHlcTh6zWrua"
}
}
如何从响应中排除user
字段?如果我删除Article.getUser
方法,一切都正常工作,响应如下:
{
"id": 5,
"text": "文章的内容..."
}
这是期望的结果。然而,我需要Article.getUser
方法,因为例如,如果有人想要删除文章,我需要检查请求的作者是否是文章的作者,以便用户不能删除其他用户的文章。
英文:
I am using Spring Boot with simple REST API on server. I have 2 resources: users and articles. Here is Article class:
@Entity(name = "article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false)
private String text;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
public User getUser() { // I need this method.
return user;
}
// All other setters and getters.
}
Now, if I fetch some article by its ID using REST API, response looks like:
{
"id": 5,
"text": "Content of article...",
"user": {
"id": 1,
"username": "user@email.com",
"password": "$2a$10$CbsH93d8s5NX6Gx/N5zcwemUJ7YXXjRIQAE2InW9zyHlcTh6zWrua"
}
}
How can I exclude user
field from response? If I remove Article.getUser
method, everything works fine and response looks like:
{
"id": 5,
"text": "Content of article..."
}
This is desired result. However, I need Article.getUser
, because e. g. if someone want delete article, I need check, if author of the request is author of the article, so user cannot delete articles of other users.
答案1
得分: 0
你可以在代码中使用 @JsonIgnore,如下所示:
@JsonIgnore
private User user;
另一种方法是使用 Projection
,通过它你可以更精确地控制响应中应包含的内容。
英文:
You can use @JsonIgnore on like below:
@JsonIgnore
private User user;
The other way is Projection
in which you have more control on what should be included in response.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论