Skip to content
Advertisement

Relations between Room Tables Android

I am developping a chat app. I have two Entities

@Entity(tableName = "messages")
public class MessageItem {
    @PrimaryKey
    private Integer msgId;
    @ColumnInfo(name = "from_id")
    private String  contact_id; 
}

And

@Entity(tableName = "contact")
public class Contact{
    @PrimaryKey
    private Integer id;
    @ColumnInfo(name = "contact_phone")
    private String  phone; 
}

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. :-

public class MessageItemWithContact {

    @Embedded
    MessageItem messageItem;
    @Relation(entity = Contact.class, parentColumn = "from_id", entityColumn = "id")
    Contact contact;
}

along with an @Query such as :-

@Transaction
@Query("SELECT * FROM messages WHERE msgId=:msgId")
MessageItemWithContact getMessageByIdWithContact(int msgId);

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

public class MessageItemWithPhone {
    @Embedded
    MessageItem messageItem;
    String phone;
}

Along with an @Query like :-

@Query("SELECT msgId, contact_phone, from_id FROM messages JOIN contact On from_id = id  ")
List<MessageItemWithPhone> getMessItemWithContactPhone();
  • 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:-

@Query("SELECT contact_phone FROM contact WHERE id=:from_Id")
String getPhoneById(String from_Id);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement