The friends database application is almost complete now, but before we can access any friends in the database, we need to create a table to keep the information in. We could leave this as an exercise for the admin that sets up the application, but we would like to make this a lot easier to use than that. A simple element that handles creating the table and likewise for removing it is a lot nicer, so let's do that.
As usual, there will be an element and a template for each new page we add, and the procedure should be fairly familiar by now. We add two elements to the repository:
<element id="INSTALL" file="install.xml" url="/install"/> <element id="REMOVE" file="remove.xml" url="/remove"/>
They are simple elements with just a confirmation button to confirm the installation and removal, so there is no need to list them here. They are located in the files classes/elements/install.xml
, classes/elements/remove.xml
, classes/templates/install.html
and classes/templates/remove.html
for those who are interested.
The install element calls a method named install
on the manager, which is where we will create the database table, by building the right query.
Example 7.12. Method to install the Friends table
public void install() throws DatabaseException { CreateTable create = new CreateTable(getDatasource()); create .table("Friend") .columns(Friend.class) .precision("firstname", 50) .precision("lastname", 50) .precision("url", 50) .nullable("firstname", CreateTable.NOTNULL) .nullable("lastname", CreateTable.NOTNULL) .nullable("description", CreateTable.NOTNULL) .nullable("url", CreateTable.NOTNULL); executeUpdate(create); // ... }
Just like the other previous queries, the bean class is used to specify which columns to create. The gain is not as big in this case since we have to set more properties than just the name and type of the columns, such as the string length and the nullable
property. Nonetheless, using the bean class makes it quite clear that the table is acting as a storage for the Friend bean, and code clarity is always a good cause.
Removing the table is done in the same way as installing it, except that DropTable
is used instead of CreateTable
.