To modify a stored entity object, retrieve it, update it, then put it back to the entity store:
Transaction txn = myDbEnv.getEnv().beginTransaction(null, null); try { Inventory iv = da.inventoryBySku.get(txn, "AlmofruiPPCLz8", LockMode.DEFAULT); iv.setVendorPrice(1.45); da.inventoryBySku.put(txn, iv); txn.commit(); } catch (Exception e) { txn.abort(); System.out.println("Aborted txn: " + e.toString()); e.printStackTrace(); }
Note that if you modify the object's primary key, then the object is stored as a new object in the entity store rather than replacing the existing object:
// Results in two objects in the store. One with SKU // 'AlmofruiPPCLz8' and the other with SKU 'my new sku'. Transaction txn = myDbEnv.getEnv().beginTransaction(null, null); try { Inventory iv = da.inventoryBySku.get(txn, "AlmofruiPPCLz8", LockMode.DEFAULT); iv.setSku("my new sku"); da.inventoryBySku.put(txn, iv); txn.commit(); } catch (Exception e) { txn.abort(); System.out.println("Aborted txn: " + e.toString()); e.printStackTrace(); }
Similarly, if you modify a secondary key for the object, the object will subsequently be accessible by that new key, not by the old one.
// Object 'AlmofruiPPCLz8' can now be looked up using "Almond Nuts" // instead of the original value, "Almonds". Transaction txn = myDbEnv.getEnv().beginTransaction(null, null); try { Inventory iv = da.inventoryBySku.get(txn, "AlmofruiPPCLz8", LockMode.DEFAULT); iv.setItemName("Almond Nuts"); da.inventoryBySku.put(txn, iv); txn.commit(); } catch (Exception e) { txn.abort(); System.out.println("Aborted txn: " + e.toString()); e.printStackTrace(); }
Finally, if you are iterating over a collection of objects using an EntityCursor, you can update each object in turn using EntityCursor.update(). Note, however, that you must be iterating using a PrimaryIndex; this operation is not allowed if you are using a SecondaryIndex.
For example, the following iterates over every Inventory object in the entity store, and it changes them all so that they have a vendor price of 1.45.
Transaction txn = myDbEnv.getEnv().beginTransaction(null, null); EntityCursor<Inventory> items = da.inventoryBySku.entities(txn, null); try { for (Inventory item : items) { item.setVendorPrice(1.45); items.update(item); } items.close(); txn.commit(); } catch (Exception e) { items.close(); txn.abort(); System.out.println("Aborted txn: " + e.toString()); e.printStackTrace(); }