|
|
You can transaction-protect your cursor operations by specifying a transaction handle at the time that you create your cursor. Beyond that, you do not ever provide a transaction handle directly to a cursor method.
Note that if you transaction-protect a cursor, then you must make sure that the cursor is closed before you either commit or abort the transaction. For example:
package db.txn; import com.sleepycat.db.Cursor; import com.sleepycat.db.Database; import com.sleepycat.db.DatabaseConfig; import com.sleepycat.db.DatabaseEntry; import com.sleepycat.db.DatabaseException; import com.sleepycat.db.Environment; import com.sleepycat.db.EnvironmentConfig; import com.sleepycat.db.LockMode; import com.sleepycat.db.OperationStatus; import com.sleepycat.db.Transaction; import java.io.File; ... Database myDatabase = null; Environment myEnv = null; try { // Database and environment opens omitted String replacementData = "new data"; Transaction txn = null; txn = myEnv.beginTransaction(null, null); Cursor cursor = null; try { // Use the transaction handle here cursor = db.openCursor(txn, null); DatabaseEntry key, data; DatabaseEntry key, data; while(cursor.getNext(key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS) { data.setData(replacementData.getBytes("UTF-8")); // No transaction handle is used on the cursor read or write // methods. cursor.putCurrent(data); } cursor.close(); cursor = null; txn.commit(); txn = null; } catch (Exception e) { if (cursor != null) { cursor.close(); } if (txn != null) { txn.abort(); txn = null; } } } catch (DatabaseException de) { // Exception handling goes here }