【发布时间】:2017-08-10 18:44:54
【问题描述】:
我的问题:我有两个实体用户评论,一个用户可以有很多评论,因此它是一对多的,其中 cmets 持有外键。问题是当我检索一些评论时,应该检索所有应该检索的内容,但它也会检索整个用户行,并且我希望在此场景中只有几列来自用户行映射,但我不想完全 JsonIgnore 那些字段.因为有一些场景,例如用户发布(也是一对多),我需要检索它们
如果你不明白,那么也许代码会让我的问题变得清晰:
代码示例: 我有两个休眠实体: 用户:
@Entity
public class User {
@Id
@GeneratedValue
private Integer id;
private String username;
@JsonIgnore
private String password;
private String about;
@JsonIgnore
@OneToMany(mappedBy="userRef")
private List<Comment> comments;
}
还有一些评论实体:
@Entity
public class Comment {
@Id
@GeneratedValue
private Long id;
private String text;
@ManyToOne
@JoinColumn(name="author_id")
private User userRef;
}
还有我在 CommentDao 中的查询(它为给定的帖子获取 cmets,这就是为什么它与 post_id 匹配,我跳过它因为我认为它与我的问题无关):
session.createQuery("from Comment c where c.postRef.id = :post_id")
.setParameter("post_id", postId).getResultList();
这会产生 JSON:
[
{
"id": 1,
"text": "Some comment text",
"userRef": {
"id": 1,
"username": "some_username",
"about": "(**I DON'T WANT THIS HERE**) Something about user"
}
}
]
我想要的 JSON 输出是一切都是一样的,只是没有关于:
[
{
"id": 1,
"text": "Some comment text",
"userRef": {
"id": 1,
"username": "some_username"
}
}
]
我尝试过的事情:
- 延迟抓取
- 在 HQL 中使用 new() 会使“about”为空
- 我知道可以在一个响应中返回,但我希望它是“嵌套的”,所以 userRef 只是 Comment 对象的一部分,因为它应该是
但另一方面,在同一个应用程序的不同场景中,我希望“关于”可以从其他一个到多个检索。
我将非常感谢任何帮助
【问题讨论】:
标签: java spring hibernate rest one-to-many