Java Reference
In-Depth Information
storage for its bank account data. Example 17-5 addresses this problem by imple-
menting a RemoteBank that uses a database to store all user account information.
After the RemoteDBBankServer creates its Connection object, it calls setAutoCom-
mit() with the argument false to turn off auto-commit mode. Then, for example,
the openAccount() method groups three transactions into a single, atomic transac-
tion: adding the account to the database, creating a table for the account history,
and adding an initial entry into the history. If all three transactions are successful
(i.e., they don't throw any exceptions), openAccount() calls commit() to commit
the transactions to the database. However, if any one of the transactions throws an
exception, the catch clause takes care of calling rollback() to roll back any trans-
actions that succeeded. All remote methods in RemoteDBBankServer use this tech-
nique to keep the account database consistent.
In addition to demonstrating the techniques of atomic transaction processing, the
RemoteDBBankServer class provides further examples of using SQL queries to inter-
act with a database. In order to run this example, you need to create a properties
file named BankDB.pr ops with database connection information. Before you run
the server for the first time, you also need to create an accounts table in the
database. You can do this by using the ExecuteSQL program to execute this SQL
statement:
CREATE TABLE accounts (name VARCHAR(20), password VARCHAR(20), balance INT);
Remember also that this is an RMI server. This means you must run the rmic com-
piler as described in Chapter 16 to generate stub and skeleton classes. You must
also start the rmir egistry service before running this program. *
Example 17−5: RemoteDBBankServer.java
package com.davidflanagan.examples.sql;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.sql.*;
import java.io.*;
import java.util.*;
import java.util.Date; // import explicitly to disambiguate from java.sql.Date
import com.davidflanagan.examples.rmi.Bank.*; // Import inner classes of Bank
/**
* This class is another implementation of the RemoteBank interface.
* It uses a database connection as its back end, so that client data isn't
* lost if the server goes down. Note that it takes the database connection
* out of "auto commit" mode and explicitly calls commit() and rollback() to
* ensure that updates happen atomically.
**/
public class RemoteDBBankServer extends UnicastRemoteObject
implements RemoteBank
{
Connection db;
// The connection to the database that stores account info
* Also, note that versions of MySQL prior to 2.23.15 don't support transactions. If you are using one of
these versions of MySQL, you may need to upgrade or switch to another database in order to run this
example.
Search WWH ::




Custom Search