Java – how do I start and continue running HSQLDB in server mode in my web application?

I don't want to use it in embedded mode because I may allow other external applications to access it And I want to start the server while Tomcat loads my application (or just when Tomcat is running) So I don't have to ask the client to run HSQLDB manually with commands or scripts before I can put my war in Tomcat and run it (to keep it simple)

I can call server from main by sending commands from Java, but this will give me an endless thread. I don't know how to deal with it Is there an easier test method to do this?

Solution

Depending on the HSQLDB document, the database may be started from Java code:

>Create a servlet "initdatabase" and use the code to start the database 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);
    }
}

>On your web XML, add the attribute load at startup and set it to 1 This is to call the method init () when the web application starts

<servlet>
    <servlet-name>InitDatabase</servlet-name>
    <servlet-class>bo.hsqltest.InitDatabase</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

When you do this, the web application will start HSQLDB in a new thread To shut down the database, you can override the destroy () method of initservlet when the application stops In the destroy method, you must execute the command "shutdown" as a normal SQL query (via JDBC)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>