Accessing a Database with Spring and JDBC Template Patterns

In earlier chapters, you learned about Spring core modules like the Spring IoC container, the DI pattern, container life cycle, and the used design patterns. Also you have seen how Spring makes magic using AOP. Now is the right time to move into the battlefield of real Spring applications with persisting data. Do you remember your first application during college days where you dealt with database access? That time, you probably, had to write boring boilerplate code to load database drivers, initialize your data-access framework, open connections, handle various exceptions, and to close connections. You also had to be very careful about that code. If anything went wrong, you would not have been able to make a database connection in your application, even though you would've invested a lot of time in such boring code, apart from writing the actual SQL and business code.

Because we always try to make things better and simpler, we have to focus on the solution to that tedious work for data-access. Spring comes with a solution for the tedious and boring work for data-access--it removes the code of data access. Spring provides data-access frameworks to integrate with a variety of data-access technologies. It allows you to use either JDBC directly or any object-relational mapping (ORM) framework, like Hibernate, to persist your data. Spring handles all the low-level code for data access work in your application; you can just write your SQL, application logic, and manage your application's data rather than investing time in writing code for making and closing database connections, and so on.

Now, you can choose any technology, such as JDBC, Hibernate, the Java Persistence API (JPA), or others. to persist your application's data. Irrespective of what you choose, Spring provides support for all these technologies for your application. In this chapter, we will explore Spring's support for JDBC. It will cover the following points:

  • The best approach to designing your data access
  • Implementing the template design pattern
  • Problems with the traditional JDBC
  • Solving problems with the Spring JdbcTemplate
  • Configuring the data source
  • Using the object pool design pattern to maintain database connections
  • Abstracting database access by the DAO pattern
  • Working with JdbcTemplate
  • The Jdbc callback interfaces
  • Best practices for configuring JdbcTemplate in the application

Before we go on to discuss more about JDBC and the template design pattern, let's first see the best approach to define the data-access tier in the layered architecture.

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

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