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 http://db.apache.org/torque/dtd/database.dtd. 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">
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);