我正在尝试为 to-many relation between Users and Articles
建模使用 GreenDAO,其中一个 User has many Articles
.
引用: GreenDAO Documentation on Relations
我的GreenDAO的生成器代码如下:
Schema schema = new Schema(1, "com.example.greendao.models");
schema.enableKeepSectionsByDefault();
schema.setDefaultJavaPackageDao("com.example.greendao.dao");
Entity user = schema.addEntity("User");
user.addIdProperty().primaryKey();
user.addStringProperty("name");
Entity article = schema.addEntity("Article");
article.addIdProperty().primaryKey().autoincrement();
article.addStringProperty("title");
article.addStringProperty("content");
Property userId = article.addLongProperty("userId").notNull().getProperty();
ToMany userToArticles = user.addToMany(article, userId);
userToArticles.setName("articles");
new DaoGenerator().generateAll(schema, "app/src/main/java");
接下来,我获取 Users
和 Articles
通过Retrofit
并将其转换为 List<User>
使用 Gson
示例 HTTP API 响应
[
{
"id": 1,
"name": "Example Name 1",
"articles": [
{
"id": 2,
"title": "Example Title 2",
"content": "Example Content 2"
},
{
"id": 10,
"title": "Example Title 10",
"content": "Example Content 10"
}
]
},
{
"id": 2,
"name": "Example Name 2",
"articles": [
{
"id": 111,
"title": "Example Title 111",
"content": "Example Content 111"
}
]
}
]
转换后,我得到一个 List<User>
第一个用户状态的对象:
- 编号:1
- 姓名:示例姓名 1
- 文章:
- 编号:2
- title:示例标题 2
- 内容:示例内容 2
- userId: null
- 编号:2
- title:示例标题 2
- 内容:示例内容 2
- userId: null
-
第一篇
-
第二条
这是我插入用户和文章的方式
daoSession.runInTx(new Runnable() {
@Override
public void run() {
for (User user : users) {
userDao.insertOrReplaceInTx(user);
articleDao.insertOrReplaceInTx(user.articles());
}
}
});
问题:
当使用 UserDao
获取用户时,并使用 getArticles()
检索文章方法,检索到正确的文章,但 userId
文章中的字段为空(这是有道理的,因为 userId 已经为空)
有没有办法在 ArticlesDAO
中插入文章, userId
的值可以自动设置为用户的 id 而不是每次都在代码中手动设置为 userId 吗?
注意外键约束已经设置好
最佳答案
你应该这样做:
daoSession.runInTx(new Runnable() {
@Override
public void run() {
for (User user : users) {
userDao.insertOrReplaceInTx(user);
for (Article article : user.getArticles()) {
article.setUser(user);
articleDao.insertOrReplaceInTx(article);
}
}
}
});
我知道它可能更漂亮,但是,据我所知,您必须为每个实体一个一个地设置用户。
关于android - 默认情况下,对于 ToMany 关系,GreenDao 外键设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36818894/