Spring JDBCTemplate with Example

JDBC produces a lot of boiler plate code, such as opening/closing a connection to a database, handling sql exceptions etc. It makes the code extremely cumbersome and difficult to read.

Implementing JDBC in the Spring Framework takes care of working with many low-level operations (opening/closing connections, executing SQL queries, etc.). We only need to define the connection parameters from the database and register the SQL query, the rest of the work for us is performed by Spring.

JdbcTemplate is the base class that does the following stuff for us.

  • creation and closing of connections
  • executing statements and stored procedure calls
  • iterating over the ResultSet and returning results

Instances of the JdbcTemplate class are thread-safe. This means that by configuring a single instance of the JdbcTemplate class, we can then use it for several DAO objects.

So let’s drill down to the coding part now.

In this example, we will read all the records of the Student Table and print it.

Table Data

Screen Shot 2020-02-08 at 7.11.52 PM

Project Structure

Screen Shot 2020-02-08 at 8.10.38 PM

pom.xml

We need to add spring-core, spring-context and spring-jdbc dependencies.

As we are connecting to MySQL DB, we have added mysql-connector-java in the dependency as well. Based on your DB, you can add the DB vendor specific jar which will have the required Driver class.

pom

database.properties

Configure database url, driver class, username and password in database.properties

Screen Shot 2020-02-08 at 8.01.54 PM

AppConfig

Configure datasource and jdbcTemplate beans here.

Screen Shot 2020-02-08 at 7.59.35 PM

Let’s now create the Student class

Student

student

JdbcTemplate maps query results to Mapper objects (Mapper class implements the RowMapper interface).

For every row returned by the query, Spring uses the row mapper to populate the java bean. Let’s create the StudentMapper class.

StudentMapper

Screen Shot 2020-02-08 at 8.00.35 PM

Let’s define the DAO classes which will have the necessary API to fetch all Student records from DB.

StudentDAO

Screen Shot 2020-02-08 at 7.59.51 PM

StudentDAOImpl

Here , we will use the query API of JdbcTemplate for fetching all Students and pass the StudentMapper object which will be used by JdbcTemplate to populate the records.

Screen Shot 2020-02-08 at 8.00.01 PM

Let’s execute the code.

MainExecutor class

Screen Shot 2020-02-08 at 8.00.17 PM

Output

Screen Shot 2020-02-08 at 7.59.06 PM

Update, Delete,Insert and Find Operations

// Added more APIs in DAO

Screen Shot 2020-02-08 at 10.27.02 PM

Screen Shot 2020-02-08 at 10.27.14 PM

Screen Shot 2020-02-08 at 10.27.28 PM

Output

Screen Shot 2020-02-08 at 10.26.39 PM

 

 

 

 

 

Leave a Reply

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