如何在ormlite中保存带有“外来对象”的对象

时间:2013-07-13 03:26:12

标签: java android sqlite orm ormlite

这是我的数据库:

CREATE TABLE other (
    id integer primary key autoincrement not null,
    texto text
);

CREATE TABLE tabela (campoid INTEGER primary key autoincrement not null, 
                        camponome text not null, chave int,
                        foreign key (chave) references other(id));

这是我的课程:

@DatabaseTable(tableName = "tabela")
public class Bean {

    @DatabaseField(columnName = "campoid", generatedId = true)
    private int _id;

    @DatabaseField(columnName = "camponome")
    private String nome;

    @DatabaseField(foreign = true, columnName = "chave", canBeNull = false)
    private Part chave;
}

和其他classe映射

@DatabaseTable(tableName = "other")
public class Part {

    @DatabaseField(generatedId = true, columnName = "id")
    private Integer id;

    @DatabaseField(columnName = "texto")
    private String texto;
}

但是当我保存Bean对象时,对象'部分'也不会保存:(

        Helper helper = OpenHelperManager.getHelper(this, Helper.class);
        Dao<Bean, Integer> dao = helper.getDao(Bean.class);

        Bean firstBean = new Bean();
        firstBean.setNome("first be persisted");

        Part part = new Part();
        part.setTexto("ANY TEXT");
        firstBean.setChave(part);

        dao.create(firstBean);

在我的日志中:

07-13 00:25:26.602:D / BaseMappedStatement(3796):使用语句'INSERT INTO tabelacamponomechave)插入数据VALUES(?,?) '和2个args,改了1行

任何想法?

1 个答案:

答案 0 :(得分:2)

  

但是当我保存Bean对象时,对象'部分'也不会保存:(

右。默认情况下,ORMLite在创建对象时不会保留子对象。您可以打开foreignAutoCreate = true标志,然后为您执行此操作。请参阅javadocs for foreignAutoCreate

您的chave字段应定义为:

@DatabaseField(foreign = true, columnName = "chave", canBeNull = false,
    foreignAutoCreate = true)
private Part chave;

如果你想手动完成,你应该:

partDao.create(firstBean.chave);
beanDao.create(firstBean);

您首先在数据库中创建Part ,因为您需要Part中的ID,该ID将保存到您的bean中。