简体   繁体   中英

How to join multiple table in Room Database

I have an abstract class like this:

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;
  ...
}

and two classes that inherit from mentioned abstract class:

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;
  ...
}

I want to make 3 tables in DB: notifications , wallpaper_notification , ringtone_notifications . But when I want to select (join) from tables to get all notifications (wallpapers and ringtones) I don't know what I need to do.

I want something like this:

@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();

But it will give me only fields that NotificationParent class contains. Not fields of subclasses. Also, I want the query to be ready to implement PagedList architecture.

Please give your suggestions even if I must change the design of classes.

Your select query looks right. But your method is not right.

public NotificationParent getAllNotifications();

This means that you want to return fields that have Notification parent.You need to make another class, for example:

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

And put in it everything from your tables. If you don't want everything you need to modify your select instead * you can put

Select notifications.date, ringtone_notifications.rtName

Your object will be like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM