Java IoT Authors: Zakia Bouachraoui, Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz

Related Topics: Java IoT

Java IoT: Article

Using JDBC and the Template Method Pattern for Database Access

Getting There With a Minimum of JDBC Knowledge

JDBC is a simple and flexible way to access a relational database. The knock on JDBC is that it forces a developer to familiarize himself with its API, whose use can often result in reams of duplicate or similar code: get a connection, execute a statement, parse a result set, etc. All of which needs to be wrapped in a try-catch block and synchronized.

However, in this article, I'll describe how to use the template method pattern to centralize an application's JDBC code into a single class that can be extended using a minimum of JDBC knowledge.

Template Method Pattern
The template method pattern is a way of expressing a single task as a series of smaller tasks, represented as methods on a base class. These methods can then be overridden in sub-classes to redefine parts of the overall behavior.

Database access can be broken into steps. For writing to the database, the steps are: get a connection, create a state-ment and execute the statement. Reading from the database requires the additional step of parsing the result set. And all of this must happen within the context of a try-catch block and a transaction.

And all this lends itself to the template method pattern.

Database access can be simplified by defining the steps needed to execute a SQL statement in a single base class. Some of these methods can be concrete and some left to be defined in the sub-class. A developer can then create sub-classes for each of the different SQL statements he plans to execute and override only those steps necessary.

The Solution
Start with an abstract base class that contains all the steps necessary for executing either a read or a write to the database using JDBC. I call my class BaseStatement (shown in class diagram 1).

The method execute() contains the steps taken to execute a statement (see Listing 1).

Get the Connection
The first step is to get a Connection to the database. This is ordinarily done from a JDBC DataSource. Listing 2 shows BaseStatement's getConnection() method.

On line 4, the method checks to see if the statement already has a Connection, and if so, it returns it. (Why the statement might already have a Connection is discussed below in the section entitled Managing Transactions) If not, on lines 7-9, the method gets a reference to the DataSource from the JNDI directory, retrieves a Connection from the DataSource pool and stores it in the member variable called connection. Before returning the Connection to the calling method, getConnection() turns off autocommit (line 12).

Prepare the Statement
The next step is to get the statement. I've chosen to use a PreparedStatement. Listing 3 shows the getPreparedStatement method as well as the following step of processing the statement (inserting the data into the SQL statement).

On line 4, the getPreparedStatement method creates a PreparedStatement from the Connection by passing to it the preparedStatementText. The preparedStatementText was passed to the BaseStatement object through the constructor and held in the member variable called preparedStatementText. The values to be inserted in the prepared statement are also passed to the Statement object via the constructor in the form of a List and stored in the member variable called arguments (see Listing 4).

Listing 4 Both the SQL text and the list of arguments to be inserted into the Statement are passed to the constructor and stored in member variables.

The processStatement method (line 7 in Listing 3) assumes that the first object in the variable, arguments, is the first value to be inserted into the PreparedStatement. The method that constructs the Statement must place the arguments in the List in the appropriate order.

This works equally well if there are no arguments. The for statement on line 11 (Listing 3) will fail immediately and no values will be inserted into the statement. This is exactly what we want when executing statements that require no processing (such as SELECT * FROM COMPANIES_TABLE).

Executing a Statement
The next step in the template is executeStatement, which will execute the statement constructed in the previous steps and return the result set (if any). It is defined as abstract in the BaseStatement class because statements that modify the database differ from query statements. Query statements are executed through the PreparedStatement's executeQuery method, which returns a ResultSet. Modifying statements call the method execute(), which returns a boolean. I'll use sub-classes to distinguish between statements that query and those that modify. These sub-classes will define the appropriate executeStatement behavior.

Querying the database
For querying the database, I've created a sub-class called SelectStatement that defines the method executeStatement() to return the ResultSet returned from a call to the method executeQuery off of the PreparedStatement (line 13 in Listing 5).

I've defined SelectStatement to be abstract because it can't define the method ParseResultSet, which is intended to convert the results of a query into Java objects and differs depending upon the data for which you are querying. The parseResultSet method will be dependent on the SQL statement passed to the SelectStatement constructor. To construct a SelectStatement, you need to extend SelectStatement and define the parseResultSet method.

Listing 6 shows a method that queries the database for dealer. This method exists on a class called DealerDAO whose sole purpose is to read and write dealer information into the database. In this example, a dealer contains an id (BigDecimal), a name and a number (both Strings). A JavaBean called DealerVO represents the (value object pattern).

Additional Patterns: I've Introduced Two New Patterns

  • Data access object (DAO) pattern: A class responsible for reading and writing certain information to the database. It hides the SQL specific code behind a clean interface. It contains methods such as create, remove, update, findByPrimaryKey and additional find Methods. It presents an object-oriented view of the data in the database. In this example, DealerDAO is responsible for writing dealers into the database.
  • Value object (VO) pattern: Represents data in the database as a JavaBean. Most often represents a row in a table or view (though it could represent a more complicated mapping). Makes the passing of this data between the application tiers easier. In this example, a dealer is represented by a DealerVO value object. DealerVO has three properties: id, name and number.

    I've chosen to extend SelectStatement with an anonymous class whose declaration begins on line 7 of Listing 6 because this statement will only be used by the DAO's create method. Should I need it elsewhere, I can redefine it as an inner class and referred to it in both places.

    I call the constructor of the SelectStatement and pass it the SQL statement to execute as well as the primary key (wrapped in a List). I further define the method parseResultSet (line 12) to convert each row of the results into a DealerVO by calling the getDealerVOFromResultSet method.

  • More Stories By Keith Reilly

    Keith Reilly is a Java architect with MFS Investment Management in Boston, MA. He can be reached at [email protected]

    Comments (18)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    IoT & Smart Cities Stories
    Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
    The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
    BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.