Chapter 6. Other Operations

Table of Contents

Deleting Entity Objects
Replacing Entity Objects

While we are done with our example application, there are several common activities that we have not yet explained: deleting entity objects and replacing them. This are fairly simple tasks, so we cover them briefly here.

Deleting Entity Objects

The simplest way to remove an object from your entity store is to delete it by its primary index. For example, using the DataAccessor class that we created earlier in this document (see DataAccessor.class), you can delete the Inventory object with SKU AlmofruiPPCLz8 as follows:

Transaction txn = myDbEnv.getEnv().beginTransaction(null, null);
try {
    da.inventoryBySku.delete(txn, "AlmofruiPPCLz8");
    txn.commit();
} catch (Exception e) {
    txn.abort();
    System.out.println("Aborted txn: " + e.toString());
    e.printStackTrace();
} 

You can also delete objects by their secondary keys. When you do this, all objects related to the secondary key are deleted, unless the key is a foreign object.

For example, the following deletes all Inventory objects that use the product name Almonds:

Transaction txn = myDbEnv.getEnv().beginTransaction(null, null);
try {
    da.inventoryByName.delete(txn, "Almonds");
    txn.commit();
} catch (Exception e) {
    txn.abort();
    System.out.println("Aborted txn: " + e.toString());
    e.printStackTrace();
} 

Finally, if you are indexing by foreign key, then the results of deleting the key is determined by the foreign key constraint that you have set for the index. See Foreign Key Constraints for more information.