房间表之间的关系 Android

Relations between Room Tables Android

我正在开发一个聊天应用程序。我有两个实体

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

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

在 MessageDao 中,我想获取与 MessageItem

中的 contact_id 相对应的 Contact phone

您可以通过三种方式执行此操作。

1) 您可以将 POJO 与 @Embedded 和 @Relation 一起使用,在这种情况下,您 return MessageItem 与联系人,例如:-

public class MessageItemWithContact {

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

连同@Query,例如:-

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

2) 或者您可以使用带有 @Embedded 的 POJO 和使用 JOIN 的 phone 的附加变量,例如:-

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

连同@Query,例如:-

@Query("SELECT msgId, contact_phone, from_id FROM messages JOIN contact On from_id = id  ")
List<MessageItemWithPhone> getMessItemWithContactPhone();
  • 不需要@Transaction,因为查询是单个事务(而之前的方法 Room 获取 MessageItem,然后构建查询以获取相关对象)。
  • 此查询获取所有 MessageItems(因为未包含 WHERE 子句)

3) 只需使用 from_Id 获取相关 MessageItem 的 phone,无需 POJO,只需使用 @Query 即可:-

@Query("SELECT contact_phone FROM contact WHERE id=:from_Id")
String getPhoneById(String from_Id);