默认情况下,GreenDao外键为ToMany关系设置为null

时间:2016-04-24 03:14:48

标签: android orm android-sqlite greendao

我正在尝试使用GreenDAO建模to-many relation between Users and Articles,其中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获取ArticlesRetrofit并使用Gson将其转换为List<User>


示例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
  •   
  • name:示例名称1
  •   
  • 文章:
  •   
          第一篇文章     
    • id:2
    •     
    • title:Example Title 2
    •     
    • 内容:示例内容2
    •     
    • userId:null
    •   
      
      
          第二篇文章     
    • id:2
    •     
    • title:Example 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已为null)

有没有办法在ArticlesDAO中插入文章后,userId的值可以自动设置为用户的ID,而不是每次在代码中手动将其设置为userId? / p>

注意已设置外键约束

1 个答案:

答案 0 :(得分: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);
             }
         }
     }
 });

我知道它可能更漂亮,但是,AFAIK,你必须逐个为每个实体设置用户。

相关问题