Updating Objects and Their Relationships Using ORMLite

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

I would like to have an idea of ​​how object relationships should / should be persisted in this structure.

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 I understand it, the recommended way to update an object Bill

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 whose relationship has changed? (in particular, a relationship with a set of persistent objects, as in the code above). Somehow I got the impression that this should be the best way to do it.

Also, if I want to use this framework, am I suppose to put both domain attributes and persistence-related attributes (like foreign and primary keys?) In my model classes. Wondering if there is a way to avoid this confusing problem.

Thanks for any help.

+3


source to share


1 answer


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



  • You must use annotation @ForeignCollectionField

    to mark the field billItems

    . This will load the collection when requested for Bill

    . See Documents in Foreign Collections .

    @ForeignCollectionField
    ForeignCollection<BillItem> billItems;
    
          

  • Instead of doing manual updates, you can create your own Dao class for Bill

    that overrides the update method update()

    and updates the internal objects itself.

+3


source







All Articles