Using TableTools starts with Step 1: defining a database schema. The database can then be accessed and manipulated in Step 2: using the TableTools Java API. This page shows how.
<?xml version="1.0"?>
<schema package="org.example" class="DatabaseSchema">
<!--
The 'tables' section declares all tables in the underlying
database. In this example, we have only one table.
-->
<tables>
<!--
The properties table is a simple key/value table which
maps keys to values.
-->
<table name="property">
<column name="name" type="string" null="false"/>
<column name="value" type="string" null="true"/>
<key type="primary">
<column ref="name"/>
</key>
</table>
</tables>
<!--
The 'views' section declares views on the actual database. A view
may just represent a table, as in our case. But a view may also
combine (join) tables. In both cases they are accessed through the
API in the same manner.
-->
<views>
<view name="property">
<table ref="property">
<column ref="name"/>
<column ref="value"/>
</table>
</view>
</views>
</schema>This schema is turned into a Java class by the Maven Schema Generation Plugin.
This is just an example of how the database could be used by viewing the properties table as a Map.
// instantiate the schema
DatabaseSchema schema = DatabaseSchema.newInstance();
// open a database connection
DialectConnection con = Connections.openConnection("jdbc:hsqldb:file:testdb");
try {
// setup the database by creating tables
try {
Schemas.createTables(schema, con);
} catch (SQLException e) {
// ignore, assuming they already exist
}
// this is our view
DatabaseSchema.View_property view = schema.view_property;
// get a Map interface to our properties table
CloseableMap<String,String> properties = Records.createMap(con, view, view.col_name, view.col_value, view.getHelper());
try {
// add some entries
properties.put("Sunday", "the usual day for elections in Germany and in France");
properties.put("Tuesday", "the usual day for elections in the United States");
properties.put("Thursday", "the usual day for elections in the United Kingdom");
// print what happens on Sundays
System.out.println(properties.get("Sunday"));
} finally {
// clean up resources used by the Map
properties.close();
}
// alternatively, add an item using a java bean
DatabaseSchema.PropertyBean p = schema.view_property.getHelper().createInstance();
p.setName("Monday");
p.setValue("Just another manic Monday.");
Records.add(con, p);
// table filters: an alternative way of finding an item in the table
TableView tab = schema.view_property;
tab = Tables.filter(tab, schema.view_property.col_name, "Monday");
for (DatabaseSchema.PropertyBean p : new RecordList<DatabaseSchema.PropertyBean>(con, tab, tab.getHelper())
System.out.println(p.getValue());
} finally {
// close the database connection
con.close();
}Supported SQL dialects are MySQL, Derby and HyperSQL.