【问题标题】:Spring data jpa repository retrieve multiple countsSpring数据jpa存储库检索多个计数
【发布时间】:2019-05-10 19:05:55
【问题描述】:

我有以下域实体: Conversation,其中有一个 Message 列表,每个消息都有一组 newFor Participant。列表中的消息尚未被阅读的人。

我正在努力编写存储库接口方法(或查询)来检索包含该参与者的许多未读消息的对话地图。

Atm 我使用以下内容仅检索对话列表:

@Query("SELECT c from Conversation c JOIN c.participants p WHERE :participant IN p")
List<Conversation> findByParticipantsIn(Participant participant, Pageable pageable);

但我需要以某种方式更新查询以包含嵌套未读消息的计数。类似的东西:

@Query("SELECT c, count(..my problem is here..) from Conversation c LEFT JOIN c.participants p WHERE :participant IN p ")
List<Object[]> findByParticipantsIn(Participant participant, Pageable pageable);

有没有人知道如何将连接添加到 count() 或者我还可以在这里使用什么?

UPD

暴露关系的实体片段:

public class Conversation {
...
    @OneToMany(cascade = CascadeType.ALL)
    private List<Message> messages = new ArrayList<>();
...
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Participant> participants = new LinkedHashSet<>();
...
}

public class Message {
...
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Participant> newFor = new HashSet<>();
...
}

参与者不知道消息对话的存在。

【问题讨论】:

  • “嵌套的未读消息”是什么意思?
  • 对话有一组消息。每条消息都有一个尚未阅读此消息的参与者的集合。
  • 你能显示ConversationMessageParticipant实体的相关部分吗? (查看关系)
  • @EugenCovaci 我已经添加了代码片段。提前致谢。
  • 本地查询对我来说似乎可行。

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


【解决方案1】:

最后我可以通过这种方式实现调用单个存储库方法检索数据的目标:

@Query("SELECT c, (SELECT COUNT(m) FROM Message m WHERE m.conversation = c AND :participant MEMBER OF m.newFor) " +
        "FROM Conversation c " +
        "WHERE :participant MEMBER OF c.participants " +
        "GROUP BY c, c.lastMessage.createdDate " +
        "ORDER BY c.lastMessage.createdDate DESC")
List<Object[]> findConversationsPerParticipant(Participant participant, Pageable pageable);

此查询根据上述数据模型检索给定 participant 的对话以及未读消息的计数。

不确定这种方法是否足够有效,但我相信它可能比对远程数据库的 2 次单独调用更快。

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 2018-05-04
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    相关资源
    最近更新 更多