我的项目中有四个实体:
Topic
,Article
,Comment
和Notification
。
一个
topic
可以有多个articles
。一个
article
可以有多个comments
。您可以为
notifications
添加多个comment
。
这些是我的实体:
@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();
}
但是此解决方案遍历所有notification
以获得topics
(显然有重复项)。从客户方获取它们将节省很多时间和精力,以防万一。 100 notifications
,例如5 topics
。
现在我想做的是遍历topics
而不是notifications
,但是我不知道如何查询。
我将不胜感激,即使只是提供一点帮助,也请至少一点正确的方向。
答案 0 :(得分:1)
如何在Comment
和Notification
实体之间添加双向关系?然后,您将可以在单个查询中执行以下操作:
List<Topic> findByArticlesCommentsNotificationsDateBetween(begin, end);