To write an object into the database, call its save() method. Depending on whether the data object was newly created or was read from the database, the corresponding row in the database table is inserted or updated. If the object is new, its primary key(s) is/are generated automatically if the id method was set to "idbroker" or "native" in the schema.xml.
As an example, consider the following code, which creates an Author object and inserts it into the database. Then the object is loaded again, modified. and updates the corresponding row in the databse.
Author stevens = new Author(); stevens.setFirstName("W."); stevens.setLastName("Stevens"); stevens.save();
If the generator properties "torque.complexObjectModel" and "torque.objectIsCaching" were not set to false at generation time, any objects which are referenced in the foreign key Lists of the object are also saved.
For example, in the following code, calling book.save() also saves the author added to the book:
Author bloch = new Author(); bloch.setFirstName("Joshua"); bloch.setLastName("Bloch"); Book effective = new Book(); effective.setTitle("Effective Java"); effective.setISBN("0-618-12902-2"); effective.setPublisher(addison); bloch.addBook(effective); bloch.save(); //also saves the book "effective"
Note that the save is only propagated in the 1->n directions of foreign
keys, not in the n->1 direction. I.e. in the above example, calling
effective.save() would NOT save the corresponding author.
If the object which save method is called is neither new nor modified,
it is not saved. Internally, this is handled via the
modifed flags of the object.
There are alternative ways to insert or update an object in the database:
you can pass the objects to the
doUpdate methods of their corresponding Peers, or you can
create a criteria object which contains the data of the object and pass
the Criteria object to the
doUpdate methods of the Peer class.
Note that if you construct a criteria, the id field is not added to the
Criteria. It is taken care of by underlying database system (or perhaps
the ID BROKER when it is in use).
The object that is returned by doInsert is the id of the newly added row.