Chapter 5. Saving and Retrieving Objects

Table of Contents

A Simple Entity Class
SimpleDA.class
Placing Objects in an Entity Store
Retrieving Objects from an Entity Store
Retrieving Multiple Objects
Cursor Initialization
Working with Duplicate Keys
Key Ranges
Join Cursors
Deleting Entity Objects
Replacing Entity Objects

To store an object in an EntityStore you must annotate the class appropriately and then store it using PrimaryIndex.put().

To retrieve and object from an EntityStore you use the get() method from either the PrimaryIndex or SecondaryIndex, whichever is most appropriate for your application.

In both cases, it simplifies things greatly if you create a data accessor class to organize your indexes.

In the next few sections we:

  1. Create an entity class that is ready to be stored in an entity store. This class will have both a primary index (required) declared for it, as well as a secondary index (which is optional).

    See the next section for this implementation.

  2. Create a data accessor class which is used to organize our data.

    See SimpleDA.class for this implementation.

  3. Create a simple class that is used to put objects to our entity store.

    See Placing Objects in an Entity Store for this implementation.

  4. Create another class that retrieves objects from our entity store.

    See Retrieving Objects from an Entity Store for this implementation.

A Simple Entity Class

For clarity's sake, this entity class is a simple a class as we can write. It contains only two data members, both of which are set and retrieved by simple setter and getter methods. Beyond that, by design this class does not do anything or particular interest.

Its implementation is as follows:

package persist.gettingStarted;

import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
import static com.sleepycat.persist.model.Relationship.*;
import com.sleepycat.persist.model.SecondaryKey;

@Entity
public class SimpleEntityClass {

    // Primary key is pKey
    @PrimaryKey
    private String pKey;

    // Secondary key is the sKey
    @SecondaryKey(relate=MANY_TO_ONE)
    private String sKey;

    public void setPKey(String data) {
        pKey = data;
    }

    public void setSKey(String data) {
        sKey = data;
    }

    public String getPKey() {
        return pKey;
    }

    public String getSKey() {
        return sKey;
    }
}