我的项目中有四个实体:
主题
、文章
、评论
和通知
。
One
topic
can have multiplearticles
.One
article
can have multiplecomments
.You can add multiple
notifications
forcomment
.
这些是我的实体:
@Entity
@Table(name = "topics")
public class Topic {
@Id
private Integer id;
private String name;
private String description;
@OneToMany(mappedBy = "article")
private List<Article> articles;
//getters & setters ommited
}
@Entity
@Table(name = "articles")
public class Article {
@Id
private Integer id;
private String name;
private String description;
@ManyToOne
@JoinColumn(name = "topic_id")
private Topic topic;
@OneToMany(mappedBy = "comment")
private List<Comment> comments;
//getters & setters ommited
}
@Entity
@Table(name = "comments")
public class Comment {
@Id
private Integer id;
private String name;
private String description;
private LocalDateTime createDate;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "article_id")
private Article article;
//getters & setters ommited
}
最后一个:
@Entity
@Table(name = "notifications")
public class Notification {
@Id
private Integer id;
private LocalDate date;
private String description;
@ManyToOne(optional = false)
@JoinColumn(name = "comment_id", nullable = false)
private Comment comment;
//getters & setters ommited
}
现在我试图实现的是获取一组在日期之间带有通知的主题。
我什至创建了一个解决方案:
public Set<Topic> getTopicsWithNotificationsBetweenDates(LocalDate begin, LocalDate end) {
return notificationRepository.findByDateBetween(begin, end)
.stream()
.map(notification-> getTopic(notification)))
.collect(Collectors.toSet());
}
private Topic getTopic(Notification notification){
return notification.getComment().getArticle().getTopic();
}
但是这个解决方案循环遍历所有通知
来获取主题
(显然有重复)。从客户那里获取它们会节省大量时间和精力,以防万一。 100 条通知
并且仅例如5 个主题
。
现在我想做的是循环遍历主题
而不是通知
,但我不知道查询应该是什么样子。
即使是一点点帮助,或者至少指出正确的方向,我都会感激不尽。
最佳答案
在 Comment
和 Notification
实体之间添加双向关系怎么样?然后您将能够在单个查询中执行您想要的操作,如下所示:
List<Topic> findByArticlesCommentsNotificationsDateBetween(begin, end);
关于java - 从另一个角度提问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014943/