Android Greendao 1:N 关系

Android Greendao 1:N relationships

我试图关联两个实体,虽然我通过关系正确地从服务器检索实体,但我不确定我是否正确地做这件事。

我有两个实体:AccountSong

其中一个Account可以有多个Song,而一个Song只能属于一个Account

在我的生成文件中,我做了以下事情:

Entity account = schema.addEntity("Account");
account.addLongProperty("id").primaryKey().notNull().getProperty();
Property accountId = account.addLongProperty("accountId").getProperty();
account.addStringProperty("name");
account.addStringProperty("comments");

Entity song = schema.addEntity("Song");
song.addLongProperty("id").primaryKey().notNull().getProperty();
Property songId = song.addLongProperty("songId").getProperty();
song.addStringProperty("name");
song.addStringProperty("artist");

ToMany accountToSongs = account.addToMany(song, accountId);
accountToSongs.setName("songs");
song.addToOne(account, songId);

当我对服务器进行 HTTP 调用时,我可以执行 account.getSongs() 并看到关系存在,但我知道当您执行 insert 进入 sqlite。

现在我需要访问 Account 模型的给定 id 的所有歌曲,但我不太确定我是否遗漏了一个步骤或者我是否错误地生成了文件.我应该为每个 account 手动设置 songs 吗?我在文件生成中的属性是否不正确?

我通过更改我的文件生成项目的构建方式设法解决了这个问题。

我改为执行以下操作:

Entity account = schema.addEntity("Account");
account.addLongProperty("id").primaryKey().notNull().getProperty();
Property accountId = account.addLongProperty("accountId").getProperty();
account.addStringProperty("name");
account.addStringProperty("comments");

Entity song = schema.addEntity("Song");
song.addLongProperty("id").primaryKey().notNull().getProperty();
Property accountId = song.addLongProperty("accountId").getProperty();
song.addStringProperty("name");
song.addStringProperty("artist");

ToMany songToAccounts = account.addToMany(song, accountId);
songToAccounts.setName("songs");
song.addToOne(account, accountId);

在创建我的外国实体的属性时,我几乎做了相反的事情。我对措辞有点困惑,但总的来说,这种方式有效。只要确保您知道当您持久化父元素时外国实体不会持久化。