I have a structure as follows:
A Conversation that has one or more Messages. Conversation and Message are each in their own tables. I created a ConversationDetailed relation POJO merging the Conversation with a list of its messages.
public class ConversationDetailed {
@Embedded
public Conversation conversation;
@Relation(
parentColumn = "id",
entityColumn = "conversation_id",
entity = Message.class
)
public List<Message> messageList;
}
So far this works as expected and found no issues. Now I am trying to create a ConversationSummary relation where there is only the most recent message belonging to that conversation and I cannot find an example of how to do this anywhere. This is what I am trying to achieve:
public class ConversationSummary {
@Embedded
public Conversation conversation;
@Relation(
parentColumn = "id",
entityColumn = "conversation_id",
entity = Message.class
)
public Message recentMessage; // <- the most recent message of this conversation
}
I know I can use the ConversationDetailed and just pick the most recent message from the list, but that means querying from the database a lot of messages without any need, when all I want is just the most recent one.
How can I achieve this using a Relation POJO like the example above?
EDIT: After trying the initial answer suggested by another user I discovered that relations are separate queries, that is the reason why queries with Relation POJOs use Transaction, so the question remains unanswered. Is there a way to specify the order of the relation item?
EDIT2: After a detailed explanation by the same user that provided the first answer I was finally able to make this work. Here's the rationale that worked for my case.
A combination of MAX with JOIN allows me to select the select the conversation with the most recent message out of all, including out of all conversations unrelated to that message. Adding GROUP BY for the conversation id split the above logic to get the MAX for each unique conversation id. After that it was a matter of applying the ORDER BY to the message creation date.
@Query(
"SELECT " +
"*, MAX(Message.date)" +
"FROM Conversation " +
"JOIN Message " +
"ON Conversation.id = Message.conversation_id " +
"GROUP BY Conversation.id " +
"ORDER BY Message.date DESC "
)
abstract List<ConversationSummary> getSummaryList();