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:
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Transaction;
...
// Environment and database opens omitted for brevity
...
try {
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"))data2str.getBytes("UTF-8"));
} catch (Exception e) {
// Exception handling goes here
}
// Start a transaction
Transaction txn = myEnv.beginTransaction(null, null);
// Open a cursor using the transaction
Cursor cursor = myDatabase.openCursor(txn, null);
try {
// Put the data. This is transactionally protected
cursor.putKeyFirst(key1, data1);
cursor.putKeyFirst(key2, data2);
} catch (DatabaseException dbe) {
// 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: " + dbe.toString());
cursor.close();
txn.abort();
throw dbe;
}
// Close the cursor and then commit the transaction
cursor.close();
txn.commit();