[英]Spring data jpa repository retrieve multiple counts
I have the following domain entities: Conversation , which has a list of Message s, each of them has a set newFor Participant s. 我有以下域实体: Conversation ,其中包含Message的列表,每个元素都有一个setNewFor Participant 。 For whom the message in a list has not been read yet. 对于谁尚未读取列表中的消息。
I'm struggling with writing a repository interface method (or query) to retrieve a map of conversations having a number of unread messages for this participant. 我正在努力编写一个存储库接口方法(或查询)来检索该参与者的对话地图,其中包含许多未读消息。
Atm I use the following to retrieve just a list of conversations: Atm我使用以下内容仅检索对话列表:
@Query("SELECT c from Conversation c JOIN c.participants p WHERE :participant IN p")
List<Conversation> findByParticipantsIn(Participant participant, Pageable pageable);
But I need to somehow update the query to be able to include the count of nested unread messages. 但是我需要以某种方式更新查询,以便能够包括嵌套的未读邮件的计数。 Something like that: 像这样:
@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);
Does anyone have any idea of how to put joins to count() or what else could I use here? 有谁知道如何将连接放入count()或在这里还有什么用?
UPD UPD
Entity fragments exposing the relationships: 实体片段公开了这些关系:
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<>();
...
}
Participant is not aware of Message and Conversation existence. 参与者不知道消息和对话的存在。
Finally I could accomplish the goal of retrieving the data invoking a single repository method this way: 最后,我可以实现以这种方式调用单个存储库方法来检索数据的目标:
@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);
This query retrieves conversations for the given participant
plus a count of unread messages in accordance with the described above data model. 该查询根据上述数据模型检索给定participant
对话以及未读消息的计数。
Not sure if this approach is efficient enough but I believe that it might work faster than 2 separate calls to a remote DB. 不知道这种方法是否足够有效,但是我认为它可能比对远程数据库的2次单独调用更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.