java - 在 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
,因为例如如果有人想删除文章,我需要检查请求的作者是否是文章的作者,所以用户不能删除其他用户的文章。
解决方案
您可以像下面这样使用@JsonIgnore:
@JsonIgnore
private User user;
另一种方式是Projection
您可以更好地控制响应中应包含的内容。
推荐阅读
- python - 如何使用 pymongo 在我的查询中插入一个新字段?
- sql-server - 如何连接多个表,一个表作为动态列,另一个表作为这些列的值
- google-custom-search - 是否可以自定义 Google 自定义搜索的 UI 和结果?
- ansible - Ansible - 查找与多个变量或组成员匹配的主机
- c# - ASP.NET Rotativa 从另一个控制器的视图生成 PDF
- html - 如何在没有类或 id 的情况下覆盖 html
- f# - F# 在 seq builder 中枚举时如何知道 bitArray 元素是 bool?
- java - 改造 call.enqueue 代码 200,但 response.body() 为空
- android - Kotlin 中带有 LiveData 的 ArrayOfNulls
- python - Opencv houghLines 未检测到线条