Solving problems with Spring JDBC

To overcome the preceding problems with core JDBC, Spring Framework provides excellent database integration with the Spring JDBC module. Spring JDBC provides the JdbcTemplate class, which helps us to remove the plumbing code, and also helps the developer to concentrate only on the SQL query and parameters. We just need to configure the JdbcTemplate with a dataSource and write code like this:

jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM CUSTOMER", Integer.class);

As we saw in the previous example, Spring provides a simplification for handling database access by using the JDBC template. The JDBC template uses core JDBC code internally and provides a new and efficient way to deal with the database. The Spring JDBC template has the following advantages, as compared to core JDBC:

  • The JDBC template cleans up the resources automatically, by releasing database connections
  • It converts the core JDBC SQLException into RuntimeExceptionswhich provides a better error detection mechanism
  • The JDBC template provides various methods to write the SQL queries directly, so it saves a lot of work and time

The following diagram shows a high-level overview of the Spring JDBC template:

The various approaches provided by the Spring JDBC for accessing the database are as follows:

  • JdbcTemplate
  • NamedParameterJdbcTemplate
  • SimpleJdbcTemplate
  • SimpleJdbcInsert
  • SimpleJdbcCall
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset