I don't want to use it in embedded mode as I may allow other external applications to access it as well. And I want to execute the startup of the server at the same time as Tomcat loads my application (or just when tomcat runs for that matter). This is so that I don't have to ask clients to manually run hsqldb with a command or script before they can put my war into tomcat and run it (to keep things simple).
I can perhaps call Server from main by sending command from Java, but this will give me a unending thread, I am not sure how to deal with that. Is there an easier tested way to do this?
According to the HSQLDB Documentation is possible start the database from Java Code: http://hsqldb.org/doc/2.0/guide/listeners-chapt.html#listeners_appstart-sect. So you can use a servlet for load the database when the web application is starting. The steps should be the following:
Create a Servlet "InitDatabase" and put the code for start the database on the method init()
@Override
public void init() throws ServletException {
super.init();
try {
System.out.println("Starting Database");
HsqlProperties p = new HsqlProperties();
p.setProperty("server.database.0", "file:/opt/db/crm");
p.setProperty("server.dbname.0", "mydb");
p.setProperty("server.port", "9001");
Server server = new Server();
server.setProperties(p);
server.setLogWriter(null); // can use custom writer
server.setErrWriter(null); // can use custom writer
server.start();
} catch (AclFormatException afex) {
throw new ServletException(afex);
} catch (IOException ioex) {
throw new ServletException(ioex);
}
}
In your web.xml add the property load on start up and set it to 1. This for call to method init() when the Web Application is starting.
<servlet>
<servlet-name>InitDatabase</servlet-name>
<servlet-class>bo.hsqltest.InitDatabase</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
After do this the Web Application will start HSQLDB in a new Thread. For shutdown the database when the application stops you can override the method destroy() of InitServlet. In the method destroy you must execute the command "SHUTDOWN" as normal sql query (through JDBC).