Reputation: 1381
I want to know how can i update foreign objects in ORMLITE ?
Let's say i have these classes
This is parent
public static class Parent {
@DatabaseField(generatedId=true,allowGeneratedIdInsert=true)
int id;
@DatabaseField
String name;
...
This is Child
public static class Child{
@DatabaseField(generatedId=true,allowGeneratedIdInsert=true)
int id;
@DatabaseField(canBeNull = false, foreign = true,foreignAutoCreate = true,foreignAutoRefresh = true, columnDefinition = "integer references parent(id) on update cascade")
Parent parent;
...
Assume that we have these values:
For Parent id=5 name = "big"
For Child id=338 Parent = {id=5,name="big"}
Here when i want to update my parent id it is working good:
firstId=5, lastId=6
UpdateBuilder<Parent, Integer> builder = ParentDao.updateBuilder();
builder.where().eq("id", firstId);
builder.updateColumnValue("id", lastId);
builder.update();
After that, I am using select command to be sure that it is updated or not. I'm sure it is updating for Parent. But when I update my Parent id, I am losing parent object in my Child object. It is appearing like this:
For Parent id=6 name = "big"
For Child id=338 Parent = {null}
Does somebody know any solution for this ?
Upvotes: 3
Views: 3053
Reputation: 116908
I want to know how can i update foreign objects in ORMLITE ?
I may not be understanding the question but the proper way to do this is to just update the child.parent
field like you would any other:
// child has a parent of #5
... child.getParent();
// update it with a new parent #6
Parent parent6 = new Parent(...);
// create the parent first so it gets an id
parentDao.create(parent6);
// set it on the child's field
child.setParent(parent6);
childDao.update(child);
This will update the fields of child
in the database. The id
field from parent will be updated from 5 to 6.
If you need to update the parent_id
field directly from 5 to 6 then you will need to refresh any existing child
objects:
childDao.refresh(child);
Upvotes: 2
Reputation: 83018
OrmLite does not auto-save nested objects automagically like other ORMs.
So you need to update Child also.
Steps are
Upvotes: 2