Android Greendao 1:N关系

时间:2016-01-13 05:20:05

标签: android sqlite greendao

我有两个实体正在尝试关联,虽然我正在通过关系正确地从服务器中检索实体,但我不确定我是否正确地执行了此操作。

我有两个实体: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。

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

1 个答案:

答案 0 :(得分:0)

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

我改为做了以下事情:

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

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

相关问题