Spring JDBC Development - Using Spring

In our first article we started talking about how to write DAOs with the help of Spring. Lets continue.

In our first article we started talking about how to write DAOs with the help of Spring. Lets continue.

Now using Spring JDBC, the code may look like this:

spring_jdbc_code.PNG

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.

jdbc_template.PNG

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.

jdbc_rowmapper.PNG

With the usage of the RowMapper, the code will look like this:

rowmapper_code.PNG
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
Interested in improving your Spring programming skills? Check out our trainings: Spring Framework for Application DevelopmentSpring Core and Spring Databases.

Catalin Tudose
Java and Web Technologies Expert

Share the knowledge

Still have questions?
Connect with us
Thank you.
Your request has been received.
Thank you!
The form has been submitted successfully.