从另一个角度查询

时间:2018-10-26 19:08:47

标签: java spring spring-data-jpa spring-data

我的项目中有四个实体: TopicArticleCommentNotification

  

一个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,但是我不知道如何查询。 我将不胜感激,即使只是提供一点帮助,也请至少一点正确的方向。

1 个答案:

答案 0 :(得分:1)

如何在CommentNotification实体之间添加双向关系?然后,您将可以在单个查询中执行以下操作:

List<Topic> findByArticlesCommentsNotificationsDateBetween(begin, end);