Saving nested foreign objects with ORMLite on Android

Chase picture Chase · Jan 20, 2011 · Viewed 23.3k times · Source

When working on Android, does ORMLite only save shallow level objects? I have a data structure with nested Objects, both of which are newly created, and I would like to be able to save both of them with one call to dao.create()

For exmaple, I have the following Parent Class.

@DatabaseTable
public class Parent {

  @DatabaseField(generatedId=true)
  public int id;

  @DatabaseField
  public String name;

  @DatabaseField
  public Child child;
}

and the following Child Class.

@DatabaseTable
public class Child {

  @DatabaseField(generatedId=true)
  public int id;

  @DatabaseField
  public String name;
}

I want to be able to do the following.

Parent parent = new Parent();
parent.name = "ParentName";

Child child = new Child();
child.name = "ChildName";

parent.child = child;

//  .. get helper and create dao object...
dao.create(parent);

When doing this, the parent object is persisted but not the child object and the auto-generated child_id column in the parent table is set to 0. Is this normal behavior? Is there a way to have nested objects persisted and propagate the primary key up?

Answer

lstrzelecki picture lstrzelecki · Mar 16, 2012

Did you try this?

@DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
public Child child;

I'm using ORMLite 4.35.