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.
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.
Configure database url, driver class, username and password in database.properties
Configure datasource and jdbcTemplate beans here.
Let’s now create the Student class
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.
Let’s define the DAO classes which will have the necessary API to fetch all Student records from DB.
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.
Let’s execute the code.
Update, Delete,Insert and Find Operations
// Added more APIs in DAO