12.  Schema Tool

Most users will only access the schema tool indirectly, through the interfaces provided by other tools. You may find, however, that the schema tool is a powerful utility in its own right. The schema tool has two functions:

  1. To reflect on the current database schema, optionally translating it to an XML representation for further manipulation.

  2. To take in an XML schema definition, calculate the differences between the XML and the existing database schema, and apply the necessary changes to make the database match the XML.

The XML format used by the schema tool abstracts away the differences between SQL dialects used by different database vendors. The tool also automatically adapts its SQL to meet foreign key dependencies. Thus the schema tool is useful as a general way to manipulate schemas.

You can invoke the schema tool through its Java class, org.apache.openjpa.jdbc.schema.SchemaTool. In addition to the universal flags of the configuration framework, the schema tool accepts the following command line arguments:

The schema tool also accepts an -action or -a flag. Multiple actions can be composed in a comma-separated list. The available actions are:

Note

The schema tool manipulates tables, columns, indexes, constraints, and sequences. It cannot create or drop the database schema objects in which the tables reside, however. If your XML documents refer to named database schemas, those schemas must exist.

We present some examples of schema tool usage below.

Example 4.14.  Schema Creation

Add the necessary schema components to the database to match the given XML document, but don't drop any data:

java org.apache.openjpa.jdbc.schema.SchemaTool targetSchema.xml

Example 4.15.  SQL Scripting

Repeat the same action as the first example, but this time don't change the database. Instead, write any planned changes to a SQL script:

java org.apache.openjpa.jdbc.schema.SchemaTool -f script.sql targetSchema.xml

Write a SQL script that will re-create the current database:

java org.apache.openjpa.jdbc.schema.SchemaTool -a createDB -f script.sql

Example 4.16.  Table Cleanup

Refresh the schema and delete all contents of all tables that OpenJPA knows about:

java org.apache.openjpa.jdbc.schema.SchemaTool -a refresh,deleteTableContents

Example 4.17.  Schema Drop

Drop the current database:

java org.apache.openjpa.jdbc.schema.SchemaTool -a dropDB

Example 4.18.  Schema Reflection

Write an XML representation of the current schema to file schema.xml .

java org.apache.openjpa.jdbc.schema.SchemaTool -a reflect -f schema.xml