Table of Contents
In order to use transactions with your application, you must turn them on. To do this you must:
Turn on transactions for your environment. You do this by using the EnvironmentConfig.setTransactional() method, or by using the je.env.isTransactional je.properties parameter.
Transaction-enable your databases. You do this by using the DatabaseConfig.setTransactional() method, and then opening the database from within a transaction. Note that the common practice is for auto commit to be used to transaction-protect the database open. To use auto-commit, you must still enable transactions as described here, but you do not have to explicitly use a transaction when you open your database. An example of this is given in the next section.
To enable transactions for your environment, you must initialize the transactional subsystem:
package je.txn;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
...
Environment myEnv = null;
try {
EnvironmentConfig myEnvConfig = new EnvironmentConfig();
myEnvConfig.setTransactional(true);
myEnv = new Environment(new File("/my/env/home"),
myEnvConfig);
} catch (DatabaseException de) {
// Exception handling goes here
}
You then create and open your database(s) as you would for a non-transactional system. The only difference is that you must set DatabaseConfig.setTransactional() to true. Note that your database open must be transactional-protected. However, if you do not give the openDatabase() method a transaction handle, then the open is automatically protected using auto commit. Typically auto commit is used for this purpose. For example:
package je.txn;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import java.io.File;
...
Database myDatabase = null;
Environment myEnv = null;
try {
EnvironmentConfig myEnvConfig = new EnvironmentConfig();
myEnvConfig.setTransactional(true);
myEnv = new Environment(new File("/my/env/home"),
myEnvConfig);
// Open the database. Create it if it does not already exist.
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setTransactional(true);
myDatabase = myEnv.openDatabase(null,
"sampleDatabase",
dbConfig);
} catch (DatabaseException de) {
// Exception handling goes here
}
Never close a database that has active transactions. Make sure all transactions are resolved (either committed or aborted) before closing the database.