首页 > 解决方案 > 从另一个角度查询

问题描述

我的项目中有四个实体 :TopicArticle和。CommentNotification

一个topic可以有多个articles

一个article可以有多个comments

您可以添加多个notificationsfor 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(显然有重复)。从客户端获取它们将节省大量时间和精力,以防出现 eg100 notifications并且只有 eg 5 topics

现在我要做的是循环topics而不是循环notifications,但我不知道我的查询应该是什么样子。即使是一点点帮助,或者至少指向正确的方向,我都会感激不尽。

标签: javaspringspring-data-jpaspring-data

解决方案


Comment在 a和Notification实体之间添加双向关系怎么样?然后,您将能够在这样的单个查询中执行您想要的操作:

List<Topic> findByArticlesCommentsNotificationsDateBetween(begin, end);

推荐阅读