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.
- Connection properties, along with a “name” and “environment” properties are defined in a connections.xml file
- The connections.xml file is bound to a CodeJohnnyConnection class with JAXB
- The current connection is specified by “name” passed in getCurrentConnection(name). That name is specified in the CodeJohnny Template
- CodeJohnny Data Provider base class loads either the PostgreSQL or MySQL provider based on the “environment” property in connections.xml
- 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.
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.
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.