:::: MENU ::::
  • Apr 04 / 2014
  • 1

Spring JdbcTemplate

Spring JdbcTemplate

Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of JDBC API.

Problems with JDBC API

We all are aware of the JDBC(Java Database Connection) to connect the Java application to database for various DML and DDL operation and storing the data in database.

  • For doing a CRUD(Create Retrieve Update Delete) operation in simple JDBC we have to write a lot of code as well as  have to think and handle each and every exception scenario.
  • We need to perform exception handling code on the database logic.
  • We need to handle transaction.
  • Repetition of all these codes from one to another database logic is a time consuming task.

EXAMPLE

Below is the basic code for a select query via JDBC.

 

 Advantages of  Spring JDBC Template over JDBC process

Spring provides a simplification in handling database access with the Spring JDBC Template, Which is in “org.springframework.jdbc.core” package.

  1. The Spring JDBC template allows to clean-up the resources automatically, e.g. release the database connections.
  2. The Spring JDBC template converts the standard JDBC SQLExceptions into RuntimeExceptions. This allows the programmer to react more flexible to the errors. The Spring JDBC template converts also the vendor specific error messages into better understandable error messages.
  3.  The Spring JDBC template offers several ways to query the database. like queryForList() returns a list of HashMaps. The name of the column is the key in the hashmap for the values in the table.
  4. More convenient is the usage of ResultSetExtractor or RowMapper which allows to translates the SQL result direct into an object (ResultSetExtractor) or a list of objects (RowMapper). Both these methods will be demonstrated in the coding.

JDBC opertations via Spring JDBC Template

We will do a CRUD operation to manipulate the State(state name) in database.

    • Create a Model class for State

    • Create a Mapper class for our model class which help to map the result set with our member variable in the State Class

    • Create a DAO Class for State which will have the methods to do the CRUD operations.It is a good practice to have Interface for all your DAO methods and then another class to implement all those methods, But for the demo/POC purpose I am doing it in the DAOImpl class directly

    • Main Class to call the DAO class methods and test all the CRUD methods

Koushik Ghosh

Koushik Ghosh

Co-founder of CodeStrive. I am a developer in Java. I love coffee, music, coding, open source technology and playing Counter Strike. Feel free to connect me ..
Koushik Ghosh

Latest posts by Koushik Ghosh (see all)

Spring AOP - Introduction
Spring MVC With JDBC Template
Pride that quarells at self-breath