Spring JDBCTemplate example

Posted on Updated on

Spring JDBC provides api support for implementing JDBC code using Spring framework. CRUD operation using Spring JDBC has been explained with example in the blog Spring JDBC. There are certain benefits of using Spring JDBC; however, there are some drawbacks as listed below:

  1. Developers are required to implement exception handling code.
  2. Developers are required to implement code which will be executed prior and post to query execution, such as making connection, statement and resultset. Once execution has finished, connections should be closed and cleaned up.
  3. Developers need to manage everything around the transactions. For example, if something went wrong while saving data to database. They have to write the code to rollback database to previous state.

To overcome above problems, Spring framework developers has come up with Spring JDBCTemplate, which handles all overhead like connection and statement management and also exception handling. Thus, providing developers to write their query and focus on business logic. Here in this tutorial we will demonstrate example of CRUD operation using spring JDBCTemplate.

Technologies used in this examples are :

  1. JDK 1.7
  2. Maven as a build tool.
  3. Spring 4.1, however you can use lower versions of spring as well.
  4. Mysql as a database.

This example has been implemented using Eclipse and maven plugin are used to create the basic folder structure for maven java project. Few other files have been included to implement this example. The final folder structure looks like the image below.

spring jdbctemplate

1) Spring JDBCTemplate dependencies.

Add Spring JDBC and mysql dependencies into the pom.xml file.

2) Table creation in Database

We are using mysql database, using which Emp table will be created with below database script.

3) Emp model object.

A model to store Emp data is required, so we’ll create Emp model class as below.

4) Mapper and Extractor class for Emp Bean.

Mapper class : It performs the actual work of mapping each row to a result object. Developers need not worry about exception handling, SQLException will be caught and handled by the calling JDBCTemplate.

Extractor class : It contains logic to create object(beans) from resultset.

5) Data Access Object (DAO) pattern

For DAO pattern, first we need to create one interface for CRUD application as below.

Now implement above interface and create EmpDaoJDBCTemplateImpl class which will contain JDBC code for CRUD operation.

6) Spring configuration file.

7) Load and Run Test class

We have created App.java class which contains simple logic to test the CRUD application.

8) Output

Stay tuned for more tutorials and examples !

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.