java - 从另一个角度查询
问题描述
我的项目中有四个实体
:Topic
、Article
和。Comment
Notification
一个
topic
可以有多个articles
。一个
article
可以有多个comments
。您可以添加多个
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();
}
但是这个解决方案会遍历所有notification
来获取topics
(显然有重复)。从客户端获取它们将节省大量时间和精力,以防出现 eg100 notifications
并且只有 eg 5 topics
。
现在我要做的是循环topics
而不是循环notifications
,但我不知道我的查询应该是什么样子。即使是一点点帮助,或者至少指向正确的方向,我都会感激不尽。
解决方案
Comment
在 a和Notification
实体之间添加双向关系怎么样?然后,您将能够在这样的单个查询中执行您想要的操作:
List<Topic> findByArticlesCommentsNotificationsDateBetween(begin, end);
推荐阅读
- git - 尝试在 github 上合并拉取请求时出错
- javascript - 常数空间,一关,日常编码问题
- ruby-on-rails - 推荐使用 ruby on rails 创建关节表的方法:rails 生成脚手架,rails 生成模型,或 rails 生成迁移?
- wordpress - 更改为 https 后,wordpress 后端重定向到空白页面
- python - 如何解决 aiohttp json 未来?
- swift - Vapor 3 API:嵌入未来
在响应对象 - c++ - 存储在类中的函数指针
- wordpress - 将 Wordpress 主域 index.php 重定向到页面(相同域)
- java - 导入 Javafx 无法解析 Eclipse JDK-11.0.1
- drupal - 你如何更新 Drupal 8 中的 class 和 id 标签?