在Android上使用ORMLite保存嵌套的外部对象

Cha*_*ase 40 android ormlite

在Android上工作时,ORMLite是否只保存浅层对象?我有一个嵌套对象的数据结构,这两个对象都是新创建的,我希望能够通过一次调用dao.create()来保存它们.

例如,我有以下父类.

@DatabaseTable
public class Parent {

  @DatabaseField(generatedId=true)
  public int id;

  @DatabaseField
  public String name;

  @DatabaseField
  public Child child;
}
Run Code Online (Sandbox Code Playgroud)

和以下儿童班.

@DatabaseTable
public class Child {

  @DatabaseField(generatedId=true)
  public int id;

  @DatabaseField
  public String name;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够做到以下几点.

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);
Run Code Online (Sandbox Code Playgroud)

执行此操作时,父对象是持久的但不是子对象,并且child_id父表中的自动生成列设置为0.这是正常行为吗?有没有办法让嵌套对象保持不变并传播主键?

lst*_*cki 47

你试过这个吗?

@DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
public Child child;
Run Code Online (Sandbox Code Playgroud)

我正在使用ORMLite 4.35.


Gra*_*ray 43

从版本4.27开始,ORMlite在字段上的注释上支持foreignAutoCreateforeignAutoRefresh设置@DatabaseField:

@DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
public Child child;
Run Code Online (Sandbox Code Playgroud)

这意味着您指定了child字段,如果在id创建父项时未设置子项上的字段,则将创建该字段.这foreignAutoRefresh意味着当检索父级时,将进行单独的SQL调用以child填充该字段.

执行此操作时,父对象是持久的但不是子对象,并且父表中自动生成的child_id列设置为0.这是正常行为吗?

您还可以通过创建父项之前创建子项来更好地控制ORMLite何时调用子对象.

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

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

parent.child = child;

// this will update the id in child
childDao.create(child);

// this saves the parent with the id of the child
parentDao.create(parent);
Run Code Online (Sandbox Code Playgroud)

还有一点需要注意的是,如果没有foreignAutoRefresh = true查询Parent对象的时间,您获取的子对象只会检索其id字段.如果id是自动生成的int(例如),则在对子对象执行更新之前,将不会检索上面的名称字段.

// assuming the id of the Parent is the name
Parent parent = parentDao.queryForId("ParentName");
System.out.println("Child id should be set: " + parent.child.id);
System.out.println("Child name should be null: " + parent.child.name);

// now we refresh the child object to load all of the fields
childDao.refresh(parent.child);
System.out.println("Child name should now be set: " + parent.child.name);
Run Code Online (Sandbox Code Playgroud)

有关此内容的更多文档,请参阅有关外部对象字段的在线页面.