Java Jangles is the application I created to demo various Java patterns and practices. Today we’re going to walk through the Jangles Data Provider Model and demonstrate how Jangles can switch between MySQL and PostgreSQL by changing a single config file property.
We’ll start with Jangles.main() and display a list of users from either MySQL or PostgreSQL depending on the app’s config.properties “dbprovider” value.
Here’s a sample of the config.properties file we use to determine if the backend is MySQL or PostgreSQL.
Before walking through the logic, here’s the current project structure so you’ll know your way around.
Okay, Jangles.main() calls JangleUI.ListUsers(), but we’re going to jump to the business layer and JangleUsers which makes the hand-off to the provider.
An important point is that we never have to change any of the application code here or in any class that came before it because JangleUsers and the UI layer does not care what database is used. The JangleDB Provider will decide that and return a List<JangleUser> object regardless of what database it’s talking to.
The database determination is made in LoadProvider() as you can see below, where JangleDB creates an instance of either the JangleMySqlDB or JanglePostgreSQLDB classes based on the “dbprovider” configuration property JangleConfiguration retrieves from config.properties.
Both JangleMySqlDB and JanglePostgreSqlDB have the same logic. Here is JanglePostgreSqlDB. In JangleMySqlDB we would be preparing MySQL connections and queries rather than PostgreSQL to support the overridden methods like GetJangleUsers().
Another benefit of the Provider model is sharing resources in JangleDB. Here is an example with PopulateJangleUserList() shared by both MySQL and PostgreSQL providers.
If you want a closer look or a hands-on with the source code covered in this post, Java Jangles is available for download on GitHub.