Sergio
Sergio

Reputation: 8670

Updating objects and their relations using ORMLite

I have just started reading about ORMLite since I am interested in using it in an Android application.

I would like to have a feeling of how object relations are/should be persisted with this framework.

For example, if I have these classes:

@DatabaseTable(tableName = "bill_items")
class BillItem{...}

@DatabaseTable(tableName = "bills")
class Bill {
  @DatabaseField String x;

  List<BillItem> billItems = new ArrayList<BillItem>;

  public void setItems(List<BillItem> billItems) {
    this.billItems = billItems;
  }
}

As far as I understand the recommended way to update a Bill object would be with something similar to:

Dao<Bill, String> billDao = DaoManager.createDao(connectionSource, Bill.class);
Bill bill = billDao.queryForId(...);

List<BillItem> billItems = ...; //some new list of items
bill.setX("some new value for X");
bill.setItems(billItems);

//saving explicitly the billItems before saving the bill. Is this correct ?
Dao<BillItem, String> billItemDao = DaoManager.createDao(connectionSource, BillItem.class);
for(BillItem billItem : billItems)
  billItemDao.update(billItem);

billDao.update(bill);

Is this the recommended way to update an object which relations have changed ? (specifically relations with a set of persistent objects, as in the code above). Somehow I had the impression that it should be a better way to do this.

Also, if I want to use this framework, am I suppose to put in my model classes both domain attributes and persistency related attributes (e.g., foreign and primary keys ?). Wondering if there is a way to avoid this mixing of concerns.

Thanks for any help.

Upvotes: 3

Views: 3326

Answers (1)

Gray
Gray

Reputation: 116908

Your code is basically correct although there are some things you can do to improve it.

  1. You should use the @ForeignCollectionField annotation to mark the billItems field. This will load the collection when you query for a Bill. See the docs on foreign collections.

    @ForeignCollectionField
    ForeignCollection<BillItem> billItems;
    
  2. Instead of doing the updates by hand each time, you can create your own Dao class for Bill that overrides the update update() method and updates the inner objects on its own.

Upvotes: 3

Related Questions