Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Foreign Objects ORMLite - ANDROID

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 ?

like image 854
Emre Koç Avatar asked Dec 28 '25 01:12

Emre Koç


2 Answers

OrmLite does not auto-save nested objects automagically like other ORMs.

So you need to update Child also.


Steps are

  1. First you get the Parent object.
  2. Read Child from that.
  3. Update Parent
  4. Now set updated parent to child
  5. Update child also.
like image 194
Pankaj Kumar Avatar answered Dec 30 '25 15:12

Pankaj Kumar


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);
like image 38
Gray Avatar answered Dec 30 '25 16:12

Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!