Embed Derby
Derby Strategy
There are lots of ways to embed Derby in Tomcat. This tutorial uses the "casual" scenario from Lance Bader's article titled "Integrating Cloudscape and Tomcat: A cookbook for adding the database manager into the servlet container", which is on IBM developerWorks (http://www.ibm.com/developerworks/db2/library/techarticle/dm-0408bader). Bader's article and sample code was developed for Cloudscape 5.1. The Fortune Server modifies that code to work with Derby.
In this scenario, starting Tomcat also boots Derby and stopping Tomcat shuts Derby down. The advantages of this approach include:
- Many web applications can connect simultaneously to the fortunes database via Tomcat.
- It's reasonably simple.
More sophisticated options are available, such as Tomcat's JNDI Datasources, which uses Jakarta-Commons database connection pooling (DBCP); however, those are also trickier to set up.
Lifecycle Interface
The org.apache.catalina.Lifecycle interface provides a standard way of starting and stopping components. You can add your own application code that listens for an event to occur, then does something appropriate.
For example, when Tomcat starts up, we'd like to load the embedded Derby driver with this JDBC code that, by now, might start looking familiar to you:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
And when Tomcat shuts down, we'd like to perform a clean shutdown, like this:
DriverManager.getConnection("jdbc:derby:;shutdown=true");
The Lifecycle interface lets us do exactly that. We have to do two things:
- Tell Tomcat we want to listen for events.
- Provide the LifecycleListener implementation with the methods for Tomcat to execute when a particular event occurs.
We tell Tomcat that we want to listen for events by registering our listener in $CATALINA_HOME/conf/server.xml:
<Listener className="examples.tutorial.derby.ServerLifecycleListener" debug="0" />
The source code for our implementation is in examples/tutorial/derby/ServerLifecycleListener.java, which gets installed in CATALINA_HOME/server/classes. You can look at that code in its entirety, but the short story is when the listener catches the Tomcat start, it executes a method that initializes Derby and when it catches Tomcat stopping, it shuts Derby down:
public void lifecycleEvent(LifecycleEvent argEvent) { if (argEvent.getType().equals(Lifecycle.START_EVENT)) { this.initializeDerby(); } else if (argEvent.getType().equals(Lifecycle.STOP_EVENT)) { this.shutdownDerby(); } }
The initializeDerby method loads the embedded driver and the shutdownDerby method shuts Derby down.