3.7 Updating an Object


It is possible to modify a persistent object in the same manner as normal Java with no additional coding required. Assuming that the class defines methods that can be used to set the fields, then the application simply needs to invoke these methods within a transaction. The JDO implementation automatically detects when a field of a persistent object has been modified and marks the field as "dirty." At commit time, the dirty fields of all the modified persistent objects are written back to the datastore as part of the transaction.

The following code snippet taken from UpdateExample.java shows how to find a previously created Author instance and change its name. To validate that the name has changed in the datastore, it is printed in a new transaction. For simplicity, it assumes that at least one author with the specified name is in the datastore:

 
 tx.begin(); Query query =   pm.newQuery(Author.class, "name == \"Keiron McCammon\""); Collection result = (Collection) query.execute(); Author author = (Author) result.iterator().next(); query.close();  author.setName("Sameer Tyagi");  tx.commit(); tx.begin(); String name = author.getName(); System.out.println("Author's name is '" + name + "'."); tx.commit(); 

The output would be as follows :

 
 Author's name is 'Sameer Tyagi'. 

If it is decided that the changes should not be written to the datastore and should be discarded instead, then the rollback() method on Transaction can be used.

The following code snippet taken from UpdateExampleWithRollback.java is the same as the previous one, except that a rollback is used instead of a commit to undo the name change:

 
 tx.begin(); Query query =   pm.newQuery(Author.class, "name == \"Keiron McCammon\""); Collection result = (Collection) query.execute(); Author author = (Author) result.iterator().next(); query.close(result); author.setName("Sameer Tyagi");  tx.rollback();  // rollback() rather than commit() tx.begin(); String name = author.getName(); System.out.println("Author's name is '" + name + "'."); tx.commit(); 

The output would be as follows:

 
 Author's name is 'Keiron McCammon'. 

Although the name of the Author instance is modified, because the transaction is rolled back, the modification is not persisted in the datastore. Therefore, when the instance is retrieved in the next transaction, the name is unchanged.



Core Java Data Objects
Core Java Data Objects
ISBN: 0131407317
EAN: 2147483647
Year: 2003
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net