Transactional Cursors

You transactionally protect a cursor by opening it using a transaction. All operations performed with that cursor are subsequently performed within the scope of that transaction. You must be sure to close the cursor before committing the transaction.

For example:

package com.sleepycat.examples.je.gettingStarted;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Transaction;

...   

Cursor cursor = null;
Database myDb = null;
Environment myEnv = null;
Transaction txn = null;

try {
    ...
    // Environment and database opens omitted for brevity
    ...
    DatabaseEntry key1 = 
        new DatabaseEntry((new String("key1")).getBytes("UTF-8"));
    DatabaseEntry data1 = 
        new DatabaseEntry((new String("data1")).getBytes("UTF-8"));
    DatabaseEntry key2 = 
        new DatabaseEntry((new String("key2")).getBytes("UTF-8"));
    DatabaseEntry data2 = 
        new DatabaseEntry((new String("data2")).getBytes("UTF-8"));

    // Start a transaction
    txn = myEnv.beginTransaction(null, null);
    // Open a cursor using the transaction
    cursor = myDb.openCursor(txn, null);

    // Put the data. This is transactionally protected
    cursor.put(key1, data1);
    cursor.put(key2, data2);
} catch (Exception e) {
    // If an error occurs, close the cursor and abort.
    // None of the write operations performed by this cursor
    // will appear in the Database.
    System.err.println("Error putting data: " + e.toString());
    try {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }

        if (txn != null) {
            txn.abort();
            txn = null;
        }
    } catch (DatabaseException dbe) {
        // Error reporting goes here
    }
} finally {
    try {
        // Close the cursor and then commit the transaction
        if (cursor != null) {
            cursor.close();
        }

        if (txn != null) {
            txn.commit();
        }
    } catch (DatabaseException dbe) {
        // Error reporting goes here
    }
}