Secondary Indices with Transaction Applications
Prev | Chapter 3. Transaction Basics | Next

## Secondary Indices with Transaction Applications

You can use transactions with your secondary indices so long as you open the secondary index so that it is transactional.

All other aspects of using secondary indices with transactions are identical to using secondary indices without transactions. In addition, transaction-protecting secondary cursors is performed just as you protect normal cursors — you simply have to make sure the cursor is opened using a transaction handle, and that the cursor is closed before the handle is either either committed or aborted. See Transactional Cursors for details.

Note that when you use transactions to protect your database writes, your secondary indices are protected from corruption because updates to the primary and the secondaries are performed in a single atomic transaction.

For example:

    package je.txn;

    import com.sleepycat.bind.tuple.TupleBinding;
    import com.sleepycat.je.Database;
    import com.sleepycat.je.DatabaseType;
    import com.sleepycat.je.DatabaseConfig;
    import com.sleepycat.je.DatabaseException;
    import com.sleepycat.je.Environment;
    import com.sleepycat.je.EnvironmentConfig;
    import com.sleepycat.je.SecondaryDatabase;
    import com.sleepycat.je.SecondaryConfig;

    import java.io.FileNotFoundException;

    ...

    // Environment and primary database opens omitted.

    SecondaryConfig mySecConfig = new SecondaryConfig();
    mySecConfig.setAllowCreate(true);
    mySecConfig.setTransactional(true);

    SecondaryDatabase mySecDb = null;
    try {
        // A fake tuple binding that is not actually implemented anywhere.
        // The tuple binding is dependent on the data in use.
        // See the Getting Started Guide for details
        TupleBinding myTupleBinding = new MyTupleBinding();

        // Open the secondary. FullNameKeyCreator is not actually implemented
        // anywhere. See the Getting Started Guide for detais.
        FullNameKeyCreator keyCreator = new FullNameKeyCreator(myTupleBinding);

        // Set the key creator on the secondary config object.
        mySecConfig.setKeyCreator(keyCreator);

        // Perform the actual open. Because this database is configured to be
        // transactional, the open is automatically wrapped in a transaction.
        //      - myEnv is the environment handle.
        //      - myDb is the primary database handle.
        String secDbName = "mySecondaryDatabase";
        mySecDb = myEnv.openSecondary(null, secDbName, null, myDb, mySecConfig);
    } catch (DatabaseException de) {
        // Exception handling goes here ...
    }

Prev | Up | Next
Transactional Cursors | Home | Configuring the Transaction Subsystem