首页 > 解决方案 > 在 Spring Boot 中隐藏 REST API 中的 ManyToOne 字段

问题描述

我在服务器上使用带有简单 REST API 的 Spring Boot。我有 2 个资源:用户和文章。这是文章类:

@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.

}

现在,如果我使用 REST API 通过其 ID 获取一些文章,响应如下所示:

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

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

{
    "id": 5,
    "text": "Content of article..."
}

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

标签: javaspring-boot

解决方案


您可以像下面这样使用@JsonIgnore:

@JsonIgnore 
private User user;

另一种方式是Projection您可以更好地控制响应中应包含的内容。


推荐阅读