领域数据库多表

Realm Database Multiple Tables

虽然我阅读了领域文档,但我对 table 和领域的概念感到困惑。 据我所知,一个领域类似于 Table,但它可以存储多个模型。 问题是,我想要多个 tables(其中一些只包含 1 class 的对象,一些包含多个 classes)但我不知道如何管理多个境界。 我希望我的 "Database" class 成为 RealmDatabase 的包装器,并且我希望其中包含多个 Table,例如 table 用于 "new songs" 和 table 对于 "best songs"。所以我所做的是:

public class Database {
//tables that I want to have
   public enum RealmType {
    SONGS_NEW, SONGS_BEST, PLAYLISTS_BEST, PLAYLISTS_MINE, PLAYLISTS_OTHERS, ALBUMS_SPECIAL, NEWS, FEED
   }

   private static final String TAG = "Database";

   Context context;
   //A realm object for each table
   Realm profileRealm;
   Realm songs_newRealm;
   Realm songs_bestRealm;
   //and so on...

// as I didn't know how to differentiate between Realms (all of them are created with Realm.getDefaultInstance(), and I think they are just one Realm. so I created a class for different configs )
private static class RealmConfigs {
        static RealmConfiguration songs_newConfig;
        static RealmConfiguration songs_bestConfig;
        //and so on..
        public RealmConfigs() {
            config();
        }

        private static void config() {
            songs_newConfig = new RealmConfiguration.Builder()
                    .name("songs_new.realm")
                    .deleteRealmIfMigrationNeeded()
                    .build();
            songs_bestConfig = new RealmConfiguration.Builder()
                    .name("songs_best.realm")
                    .deleteRealmIfMigrationNeeded()
                    .build();
        }
    }
}

但就是感觉不对。我知道我对 Realm 的核心概念感到困惑,但文档也没有帮助。如果能清楚地解释如何正确管理不同的 Table 并初始化它们,我们将不胜感激。

PS。我也找到了这个答案,但感觉也不对:

几点:

每个领域配置将转换为一个数据库。 每个扩展 realobject 的 class 将被转换为一个 table。 这些 classes 的每个实例都将转换为一行(如果您保存它)。

首先尝试确定您需要多少个数据库和 tables? (99% 的应用程序使用 1 个数据库)。您可以阅读并遵循数据库规范化方法,然后尝试使用 Realm 实现您需要的内容。

As I know a realm is a like Table, but it can store multiple Models

1个Realm是1个数据库文件,可以存储多个RealmModels。

每个RealmModel对应1个"table".

PS. I found this answer as well but it doesn't feel right either:

那是因为该答案用于将给定 class 的子类型存储在相同的 table 中。尽管从技术上讲,即使在您的设置中也是可能的。

public class Playlist extends RealmObject {
    @Index
    private String type; // SONGS_NEW, SONGS_BEST, PLAYLISTS_BEST, PLAYLISTS_MINE, PLAYLISTS_OTHERS, ALBUMS_SPECIAL, NEWS, FEED

    private RealmList<Song> songs;
}

然后

public RealmResults<Song> getSongsForType(Realm realm, RealmType type) {
    return realm.where(Playlist.class).equalTo("type", type.name())
                .findFirst().getSongs().where().findAll();
}

我也是 Realm 的新手,从 SQL Lite 切换过来,我想知道如何替换 tables 因为我读到的关于 Realm 的内容是它存储对象。 下载 Realm Studio 后,我明白了 Realm 是如何存储数据的。

这就是我所看到的以及如何根据您的情况获得倍数 table。

当您创建 Realm 对象时,它基本上会创建一个 table,其中包含基于对象属性键的字段。所以你不必 table 相同的对象或者它只是没用,因为它们是相同的

对于您的情况,歌曲只需要一个 table,然后还有其他 table(songs_new 和 songs_best)和这些 table s 将包含一个引用 songs_table 中项目的键,基本上是一个外键。