The resource management problem

Let's understand the resource management problem with the help of a real example. You must've ordered pizza online sometime. If so, what are the steps involved in the process, from the time of ordering the pizza till its delivery? There are many steps to this process--We first go to the online portal of the pizza company, select the size of the pizza and the toppings. After that, we place our order and check out. The order is accepted by the nearest pizza shop; they prepare our pizza accordingly, put the toppings on accordingly, wrap this pizza in the bag, the delivery boy comes to your place and hands over the pizza to you, and, finally, you enjoy your pizza with your friend. Even though there are many steps to this process, you're actively involved in only a couple of them. The pizza company is responsible for cooking the pizza and delivering it smoothly. You are involved only when you need to be, and other steps are taken care of by the pizza company. As you saw in this example, there are many steps involved in managing this process, and we also have to assign the resources to each step accordingly such that it is treated as a complete task without any break in the flow. This is a perfect scenario for a powerful design pattern, the template method pattern. The Spring framework implements this template design pattern to handle such type scenarios in the DAO layer of an application. Let's see what problems we face if we don't use Spring, and work with the traditional application instead.

In a traditional application, we work with the JDBC API to access the data from the database. It is a simple application where we access and persist the data using the JDBC API, and for this application, the following steps are required:

  1. Define the connection parameters.
  2. Access a data source, and establish a connection.
  3. Begin a transaction.
  4. Specify the SQL statement.
  5. Declare the parameters, and provide parameter values.
  6. Prepare and execute the statement.
  7. Set up the loop to iterate through the results.
  8. Do the work for each iteration--execute the business logic.
  9. Process any exception.
  10. Commit or roll back the transaction.
  11. Close the connection, statement, and resultset.

If you use the Spring Framework for the same application, then you have to write the code for some steps of the preceding list of steps, while spring takes care of all the steps involving the low-level processes such as establishing a connection, beginning a transaction, processing any exception in the data layer, and closing the connection. Spring manages these steps by using the Template method design pattern, which we'll study in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset