隐藏Spring Boot中REST API中的ManyToOne字段

huangapple go评论101阅读模式
英文:

Hide ManyToOne field in REST API in Spring Boot

问题

我在服务器上使用Spring Boot创建了一个简单的REST API。我有两个资源:用户(users)和文章(articles)。以下是Article类的代码:

  1. @Entity(name = "article")
  2. public class Article {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private int id;
  6. @Column(nullable = false)
  7. private String text;
  8. @ManyToOne(fetch = FetchType.LAZY)
  9. private User user;
  10. public User getUser() { // 我需要这个方法。
  11. return user;
  12. }
  13. // 其他所有的setter和getter方法。
  14. }

现在,如果我通过REST API根据文章的ID获取一些文章,响应如下:

  1. {
  2. "id": 5,
  3. "text": "文章的内容...",
  4. "user": {
  5. "id": 1,
  6. "username": "user@email.com",
  7. "password": "$2a$10$CbsH93d8s5NX6Gx/N5zcwemUJ7YXXjRIQAE2InW9zyHlcTh6zWrua"
  8. }
  9. }

如何从响应中排除user字段?如果我删除Article.getUser方法,一切都正常工作,响应如下:

  1. {
  2. "id": 5,
  3. "text": "文章的内容..."
  4. }

这是期望的结果。然而,我需要Article.getUser方法,因为例如,如果有人想要删除文章,我需要检查请求的作者是否是文章的作者,以便用户不能删除其他用户的文章。

英文:

I am using Spring Boot with simple REST API on server. I have 2 resources: users and articles. Here is Article class:

  1. @Entity(name = "article")
  2. public class Article {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private int id;
  6. @Column(nullable = false)
  7. private String text;
  8. @ManyToOne(fetch = FetchType.LAZY)
  9. private User user;
  10. public User getUser() { // I need this method.
  11. return user;
  12. }
  13. // All other setters and getters.
  14. }

Now, if I fetch some article by its ID using REST API, response looks like:

  1. {
  2. "id": 5,
  3. "text": "Content of article...",
  4. "user": {
  5. "id": 1,
  6. "username": "user@email.com",
  7. "password": "$2a$10$CbsH93d8s5NX6Gx/N5zcwemUJ7YXXjRIQAE2InW9zyHlcTh6zWrua"
  8. }
  9. }

How can I exclude user field from response? If I remove Article.getUser method, everything works fine and response looks like:

  1. {
  2. "id": 5,
  3. "text": "Content of article..."
  4. }

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,如下所示:

  1. @JsonIgnore
  2. private User user;

另一种方法是使用 Projection,通过它你可以更精确地控制响应中应包含的内容。

英文:

You can use @JsonIgnore on like below:

  1. @JsonIgnore
  2. private User user;

The other way is Projection in which you have more control on what should be included in response.

huangapple
  • 本文由 发表于 2020年10月18日 16:51:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64411415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定