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

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

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.

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:

确定