Spring JDBC Development - Using Spring
Now using Spring JDBC, the code may look like this:
JdbcTemplate is the central class to support work with JDBC from Spring. Using it, we do not have to open/close connections or handle exceptions. The JdbcTemplate is configured into application-context.xml.
With Spring support, the work to be done is much shorter:
- Specify the statement
- Do the work for each iteration
As mentioned, JdbcTemplate is the central class in the package org.springframework.jdbc.core, having as purposes to:
- Execute SQL queries
- Iterate over results
- Catch JDBC exceptions
The necessary parameters when executing an SQL query are:
- The DataSource
- The RowMapper
- The SQL query row
The RowMapper is mapping data from the database to the object model. Its role is to synchronize the business objects layer and the persistence layer.
With the usage of the RowMapper, the code will look like this:
Conclusions
The article has presented, through an example, the advantages of using Spring JDBC versus plain JDBC. The classes involved into building a Spring JDBC application are:
- javax.sql.DataSource - it controls database connections
- JdbcTemplate - the central class that controls queries execution
- RowMapper – the class that controls the mapping of each query row
Catalin Tudose
Java and Web Technologies Expert