Skip to content
Advertisement

Relations between Room Tables Android

I am developping a chat app. I have two Entities

JavaScript

And

JavaScript

In MessageDao I want to get Contact phone correponding to the contact_id in MessageItem

Advertisement

Answer

You have three ways you can do this.

1) You can use a POJO with an @Embedded and an @Relation in which case you return MessageItem’s with the Contact e.g. :-

JavaScript

along with an @Query such as :-

JavaScript

2) Or you can use a POJO with an @Embedded and an additional variable for the phone using a JOIN e.g. :-

JavaScript

Along with an @Query like :-

JavaScript
  • doesn’t need @Transaction as the query is a single transaction (whilst the previous method Room obtains the MessageItem and then builds a query to get the related object(s)).
  • this query gets all MessageItems (as no WHERE clause has been included)

3) Just get the phone using the from_Id for the relevant MessageItem without the need for a POJO by having an @Query like:-

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement