首页 > 解决方案 > 如何在房间数据库中加入多个表

问题描述

我有一个像这样的抽象类:

public abstract class NotificationParent {
  @SerializedName(SerCons.C_NOTIFICATION_ID) private int notificationId;
  @SerializedName(SerCons.C_ID) private int id;
  @SerializedName(SerCons.C_DATE) private long date;
  ...
}

和两个从提到的抽象类继承的类:

public class NotifNewRingTone extends NotificationParent {
  @SerializedName(SerCons.C_GAME_ID) private int rtId;
  @SerializedName(SerCons.C_GAME_NAME) private String rtName;
..
}
public class NotifNewWallpaper extends NotificationParent {
  @SerializedName(SerCons.C_GAME_ID) private int wpId;
  @SerializedName(SerCons.C_GAME_NAME) private String wpName;
  ...
}

我想在 DB 中创建 3 个表:notifications, wallpaper_notification, ringtone_notifications. 但是当我想从表中选择(加入)以获取所有通知(壁纸和铃声)时,我不知道我需要做什么。

我想要这样的东西:

@Query("select * from notifications n left join ringtone_notifications r on n.notif_id = r.notif_id left join wallpaper_notifications w on n.notif_id = w.notif_id) public NotificationParent getAllNotifications();

但它只会给我 NotificationParent 类包含的字段。不是子类的字段。另外,我希望查询准备好实现 PagedList 架构。

即使我必须更改课程的设计,也请提出您的建议。

标签: androidandroid-roomandroid-architecture-components

解决方案


您的选择查询看起来正确。但是你的方法不对。

public NotificationParent getAllNotifications();

这意味着您要返回具有 Notification 父级的字段。您需要创建另一个类,例如:

public class MyObject {
    private int notificationId;
    private int id;
    private long date;
    private int rtId;
    private String rtName;
    private int wpId;
    private String wpName;
 }

把你桌子上的所有东西都放进去。如果您不想修改您的选择所需的所有内容*您可以输入

Select notifications.date, ringtone_notifications.rtName

您的对象将是这样的:

public class MyObject {
        private long date;
        private String rtName;
     }

推荐阅读