问题:我无法使用 greenDao 将没有 id 的 gson 创建对象插入数据库
设置绿道
我的网络服务返回这样的输出
[
{
id: 2,
firstName: "John",
lastName: "Cleese",
dateOfBirth: -952473600,
profession: {
name: "Actor",
description: "TV show entertainer"
}
}
]
Gson
把它变成一个有Person
对象的Profession
对象。这些类使用GreenDao Generator
.
Schema schema = new Schema(SCHEMA_VERSION, "com.example.dao");
Entity profession = schema.addEntity("Profession");
profession.addIdProperty().autoincrement().notNull();
profession.addStringProperty("name");
profession.addStringProperty("description");
Entity person = schema.addEntity("Person");
person.addIdProperty();
person.addStringProperty("firstName");
person.addStringProperty("lastName");
person.addDateProperty("dateOfBirth");
Property professionProperty = person.addLongProperty("profession_id").getProperty();
person.addToOne(profession, professionProperty);
new DaoGenerator().generateAll(schema, "my/path/java");
插入问题:
现在我正在尝试像这样插入创建的Person
对象及其Profession
对象:
DaoMaster master = new DaoMaster(devOpenHelper.getWritableDatabase());
DaoSession session = master.newSession();
PersonDao personDao = session.getPersonDao();
List<Person> people = myWebServiceResponse.getPeople();
ProfessionDao professionDao = session.getProfessionDao();
personDao.insertOrReplaceInTx(people);
for (Person person : people) {
try {
professionDao.insertInTx(person.getProfession());
} catch (Exception e) {
Log.e("MainActivity", "Issue on insert: " + e.getMessage());
}
}
person.getProfession()
抛出此异常:尝试在空对象引用上调用虚拟方法“long com.example.dao.Profession.getId() ”
如果我扭转局面,通过插入第Profession
一个然后是对象,它会在同一个调用中Person
抛出Entity is detached from DAO contextperson.getProfession()