Multiple Database Connections With JAXB

We're going to look at how to support multiple database connections with JAXB using the CodeJohnny Java Code Generator architecture. The process goes like this.

  1. Connection properties, along with a “name” and “environment” properties are defined in a connections.xml file
  2. The connections.xml file is bound to a CodeJohnnyConnection class with JAXB
  3. The current connection is specified by “name” passed in getCurrentConnection(name). That name is specified in the CodeJohnny Template
  4. CodeJohnny Data Provider base class loads either the PostgreSQL or MySQL provider based on the “environment” property in connections.xml
  5. The MySQL or PostgreSQL Connection is wired-up using the current CodeJohnnyConnection properties


First the connections.xml file. NAME is used to determine the current connection for populating the CodeJohnny template, specified in the template's “connection” property. The first “default” connection is used if no specific connection is entered in the template. ENVIRONMENT loads the MySQL or PostgreSQL data provider. USER, PASSWORD, DATABASE and URLBASE define the connection.

JAXB Binding

We'll need two classes, CodeJohnnyConnections and CodeJohnnyConnection. JAXB magic in CodeJohnnyConnections includes @XmlRootElement and @XmlAccessorType, and a single @XmlElement label.

In CodeJohnnyConnection we'll define the @XmlRootElement, @XmlAccessorType and we're good.

Current CodeJohnnyConnection

We'll establish the current CodeJohnnyConnection when binding the XML file, then we'll cache it.

Using Current Connection in Data Provider

As mentioned earlier, we'll use the ENVIRONMENT property of the current CodeJohnnyConnection to load either the MySQL or PostgreSQL provider. Here in the PostgreSQL data provider class we use the remaining properties to establish the connection.

Posted March 30, 2014 12:48 PM EDT

More Like This Post