Saving Object Hierarchies
Let's assume I have an object called CTransaction. I give it a LoadData
method so it can fetch itself from the database and populate its own properties.
I should really represent a Transaction with 2 objects,
one which has all the Properties and Methods of a Transaction
and another which just worries about loading and saving Transactions. I'll
call the second one CTransactionDB.
Nothing too original there.
I should now be able to create a CTransaction object set it's
properties and call 'Save'. CTransaction would create an instance of CTransactionDB
and would pass all of it's properties to CTransactionDB in one go. It could
then call the 'Save' method of CTransactionDB which would take care of the
From what I can gather most people seem to think that the interface of DB
objects is pretty standard, you provide some way to Load, Save and Delete
and not much else. You certainly don't
mimick the properties of the Business object.
But here's a problem. Let's assume that you now want to create
a CBatch object which will contain a collection of CTransactions.
I can add Transactions to the Batch in the Client app without
ever hitting the database. Eventually I will want to
save the Batch, and all it's associated transactions.
Let's complicate things be saying that when the Batch is
saved its ID is generated by an AutoIncrement field. So
to get the ID of the batch we have to hit the database.
But let's also assume that each Transaction has a Batch
We can't set the Batch property for the Transactions until
we have hit the database to save the Batch and thus generate
So our Options seem to be:
1. Save the Batch first, without saving any Transactions.
Have the Batch ID passed back from the Batch Save
so that you can then set the Batch properties of the
transactions in the Business layer. When they have been
updated you can then save them.
Problem: This involves an extra trip to the database.
Ideally we'd like the entire Batch and Transactions to
get saved in one trip. Apart from the performance issue,
it just feels like it should happen in one place.
2. The Second option is to send the Batch and All the
transactions to be saved at the same time. When the
Batch get's saved it could iterate through it's
Transactions and set their Batch property.
Problem: I said earlier that DB objects shouldn't have
properties. Is this a special case? I hate special
I'd appreciate any thoughts. This problem can get very messy
if you allow hierarcies of arbitrary depth. Is there any
consensus on saving object hierarchies? The books seem
to take very simple examples, as usual.
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center