2016-04-24 120 views
1

我试图使用GreenDAO为to-many relation between Users and Articles建模,其中一个User has many Articles默认情况下,GreenDao外键设置为空ToMany关系

参考: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"); 

接下来,我通过RetrofitUsersArticles和使用GSON


将其转换为List<User> Sampl Ë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>对象,其中第一用户的状态是:

  • ID:1
  • 名称:实例名称1
  • 文章:
    • 第一篇文章
    • id:2
    • 标题:实施例名称2
    • 含量:实施例内容2
    • 用户名:空

      第二制品
    • ID:2
    • 标题:实施例名称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()方法,正确的文章检索,但第字段为空(这是有道理的,因为用户id为空的话)

有没有一种方式,当在ArticlesDAO物品插入,userId值可以自动设置为用户的ID,而不是手动设置它每次在代码中的userId?

注意外键约束已设置已经

回答

1

你应该做这样的事情:

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

我知道这可能是更漂亮,但是,据我所知,你要设置用户的每个实体一个接一个。

相关问题