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?
HSQLDB (HyperSQL DataBase) is the leading SQL relational database system written in Java. It offers a small, fast multithreaded and transactional database engine with in-memory and disk-based tables and supports embedded and server modes. It includes a powerful command line SQL tool and simple GUI query tools.
HSQLDB (HyperSQL Database) HSQLDB is an open source project, also written in Java, representing a relational database. It follows the SQL and JDBC standards and supports SQL features such as stored procedures and triggers. It can be used in the in-memory mode, or it can be configured to use disk storage.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With