查看完整版本: Make Java DB Your Client-side Portable Database

huxinisme 2007-2-28 23:14

Make Java DB Your Client-side Portable Database

An exclusive, embedded database for a Java application is a marvelous idea, the full potential of which may not be realized for some time. Currently, you could use it as a supplemental client-side database in desktop and browser applications or as a backup database should something go wrong with the network database.

A networked database serves as a persistence repository for various applications' business data, but every application contains a lot of data that is not business-related, such as user personal screen settings, etc. Storing this non-business-related data in a networked database server wastes valuable network and database resources. Having this type of data available only during the lifetime of the application makes sense. Java DB offers a perfect solution in this case.

Java DB is a 100 percent Java-based, lightweight RDBMS that can be run with any standard Java Virtual Machine. Though lightweight, it meets the ACID (Atomic, Consistent, Isolation, Durable) properties of the relational database system. As such, it will recover data up to before a crash without losing committed data or risking corruption. It supports all the relational database standards such as SQL and JDBC. As a result, it is platform independent and interoperable with any open standards-based database.

While Java DB provides various features, of most interest to the developer are the abilities to create XML schemas on the fly using XML files and insert rows into a table without using SQL. Traditionally developers used SQL to process DML statements from Java, but Java DB enables them to accomplish the same task without SQL. This article explores in detail these features and demonstrates them with a sample application that stores and retrieves user settings in an embedded database using Swing.


The DdlUtils Component
Java parsers provide an easy way to parse and navigate complex XML documents. The DdlUtils component is based on a similar concept, providing utilities to enable direct data navigation and manipulation inside database tables from Java code. You can create an entire database schema in XML on the fly using DdlUtils, and DdlUtils also supports reverse engineering of existing schemas into XML or Java objects. So while Java DB takes care of database-related functionality such as transaction management, concurrency, backups, etc., DdlUtils handles interactions with the database.


Create XML Schemas on the Fly
Java DB provides features for creating a database when an application starts and deleting it by simply deleting the data files directory. With this approach, the database is no longer a separate entity. Instead, it is part of your code and you have exclusive control over it. To demonstrate these Java DB features, the remainder of this article walks you through the creation of a golf course finder application. When you launch the sample application, it also will launch an embedded Java database. And when the application shuts down, the database does also. Although it is a desktop application, you can run it on any platform because it is standard Java (e.g., it makes a lot of sense as a mobile app).
First, download the accompanying code for this article. It includes derby.jar (Java DB) and DdlUtils.jar. The remaining contents are from Jakarta Commons. They help to compile the code.

Next, create a database schema XML file according to schema rules published in [url]http://db.apache.org/torque/dtd/database.dtd.[/url] Use DdlUtils to read and parse the XML into a Database model Java object.

The following code snippet represents in XML the database schema of the golf course finder application:


<!DOCTYPE database SYSTEM "http://db.apache.org/torque/dtd/database.dtd">
<database name="testdb">
  <table name="userData">
      <column name="userName"
              type="VARCHAR"
              primaryKey="true"
              size="20"
              required="true"/>
      <column name="password"
              type="VARCHAR"
              size="20"
              required="true"/>      
  </table>

The following code snippet constructs a Database model Java object from the above XML:


// filename represents the database schema in XML format
public Database readDatabaseFromXML(String fileName)
{
    return new DatabaseIO().read(fileName);
}

Finally, create database tables using the Platform class:


// derby is synonym for Java DB
Platform platform = PlatformFactory.createNewPlatformInstance("derby");
platform.createTables(conn, database, true, true);


Insert Data into Tables Without SQL
DdlUtils uses the DynaBean class to alter table data. A typical bean has fixed properties and has setter and getter methods for those properties. A DynaBean, as the name indicates, allows dynamic creation of the bean properties. A DynaBean is a Java object that supports properties whose names and data types, as well as values, may be dynamically modified. In this case, the properties are nothing but the column names and column values of the underlying tables.
The following code creates a Java object of table data and inserts it into the table using a platform class:


//insert data into table without SQL insert statement
DynaBean userData = database.createDynaBeanFor("userData", false);
userData.set("userName",     "tiger");
userData.set("password",     "singh");
platform.insert(conn, database, userData);

This code technique eliminates the hassle of creating a java.sql.Statement and a java.sql.ResultSet. More importantly, it eliminates having to verify that they are all closed to prevent the application from failing with too many open cursors.


Platform and Database Classes
Among others, the platform and database classes are the important ones in the derby.jar.
The platform interface provides the database-related functionality for processing DML statements such as queries and manipulations. It also contains a SQL builder that is specific to that particular platform. DdlUtils provides separate implementation classes for each database platform. In the sample application, for instance, the platform was "Derby".

The database class represents the database model (i.e., the tables in the database). It also contains the corresponding dyna classes for creating DynaBeans for the objects stored in the tables. A Table class, as the name indicates, represents a Java object for the database table. All DDL statements can be processed using Database and Table classes.


Running the Application
As DdlUtils is still in development and has no binary release as of the writing of this article, you can get the code from the repository and do a build (Method 2), or you can use the jars from the extjars folder in the code download (Method 1).
The following are the instructions for the two methods:

Method 1:


Install the code download in your favorite C drive or D drive.
Rename cp.bat_txt to cp.bat.
Edit cp.bat and change <INSTALL_DIR>.
Open a command prompt window and run cp.bat.
Goto: <INSTALL_DIR>\demo.
Compile: $> javac MySimpleApp.java.
Run: $> java MySimpleApp DBSchema.xml.
Method 2:

Download Java DB from developers.sun.com.
Download DdlUtils from [url]http://db.apache.org.[/url]
As there is no binary distribution available at this time for DdlUtils, you have to download all Jakarta Commons packages from jakarta.apache.org/commons:
commons-beanutils.jar
commons-betwixt-0.7.jar
commons-collections-3.1.jar
commons-digester-1.7.jar
commons-lang-2.1.jar
commons-logging.jar
Include all the packages in the class path to compile MySimpleApp.java (from the code download) and run.
When the application starts, it instantiates the database. It then reads the database schema from the XML file and creates the schema. Data related to two users is inserted using DynaBeans. The application has a user interface for capturing the username and password from the user and validates it against the password stored in the embedded database (see Figure 1).  
[attach]1427[/attach]

Figure 1. Initial Screen Using tiger/singh or vijay/woods to Login


Upon successful login, the next screen provides a list of available famous golf courses on the left-hand side and a list of golf courses the user has played on the right-hand side (see Figure 2).
[attach]1428[/attach]

Figure 2. Golf Courses Listed on the Right Are Pulled from Java DB


The application reads the list of golf courses the user has played from the database while launching the screen in Figure 2. As the database is used in embedded mode, it will shut down when the application is terminated.


Think of the Possibilities
What can be accomplished with an embedded Java database is left to the imaginations of software architects and developers. I am sure that a few years from now we will see many Java DB-backed interactive applications with zero downtime. Currently, plans are in the works to use Java DB as a repository for office productivity documents in Microsoft Office and OpenOffice, and in many of the new breed of AJAX-driven offerings. More importantly, Java DB addresses many of the functionality problems for mobile applications such as data replication.


Raghu Donepudi is a Lead Systems Developer for Global Computer Enterprises. He has a Masters degree in Computer Science from Lamar University in Texas. He is a Sun-certified Java developer and the author of many software design techniques.
页: [1]
查看完整版本: Make Java DB Your Client-side Portable Database