One-To-Many relationship in ORMLite Android

混江龙づ霸主 提交于 2019-12-03 17:31:25

问题


How do I implement one-many relationship in ORMLite Android?

please find the example

public class A {
 private String name;
    @DatabaseField (foreign = true, foreignAutoRefresh = true, columnName = "A")
    private B b;
    @DatabaseField(columnName = "author")
    private String authorName;
}

public class B {
    @DatabaseField(generatedId = true, columnName = "id")
    private long id;
    @DatabaseField(columnName = "name")
    private String name;
    @ForeignCollectionField
    Collection<A> aees;
}

B has collection of A. I am calling dao.create(b);

Now i create dao of b, since b has all the data. But the table B has only created with data, A is never created. Kindly could some one help?


回答1:


Now i create dao of b, since b has all the data. But the table B has only created with data, A is never created. Kindly could some one help?

Right. You need to create the A items using:

for (A a : b.aees) {
   aDao.create(a);
}

ORMLite does not automatically create those for you.

You might take a look a the source code of the foreign-collection example program.




回答2:


You have to override the DAO of the B class, so when an object B is created or updated, the objects in the collection to be also updated.

Take a look at this question: Collections in ORMLite.




回答3:


i was facing the same problem. My json was like:

{
   "parent":{
            "name":"ABC",
            "children":[
                          {"childName":"1"},
                          {"childName":"2"},
                          {"childName":"3"}
                       ]
             }
}

i resolved the issue like this:

Parent parent = new Parent();
parent.setName("ABC");

while(get children one by one from json data)
{
    childrenArray.add(new Child(its Name));
}

parentDAO.create(parent);

for(Child child : childrenArray)
{
    child.setParent(parent);
    childDAO.create(child);
}


来源:https://stackoverflow.com/questions/17441694/one-to-many-relationship-in-ormlite-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!