Solving problems with Spring's JdbcTemplate

Spring's JdbcTemplate solves both the problems listed in the last section. JdbcTemplate greatly simplifies the use of the JDBC API, and it eliminates repetitive boilerplate code. It alleviates the common causes of bugs, and handles SQLExceptions properly without sacrificing power. It provides full access to the standard JDBC constructs. Let's see the same code using Spring's JdbcTemplate class to solve these two problems:

  • Removing redundant code from the application using JdbcTemplate: Suppose you want a count of the accounts in a bank. The following code is required if you use the JdbcTemplate class:
        int count = jdbcTemplate.queryForObject("SELECT COUNT(*)
FROM ACCOUNT", Integer.class);

If you want to access the list of accounts for a particular user ID:

        List<Account> results = jdbcTemplate.query(someSql,
new RowMapper<Account>() { public Account mapRow(ResultSet rs, int row) throws
SQLException { // map the current row to an Account object } });

As you can see in the preceding code, you don't need to write the code for Open and Close database connection, for preparing a statement to execute query, and so on.

  • Data Access Exceptions: Spring provides a consistent exception hierarchy to handle technology-specific exceptions like SQLException to its own exception class hierarchy with DataAccessException as the root exception. Spring wraps these original exceptions into different unchecked exceptions. Now Spring does not force the developers to handle these exceptions at development time. Spring provides the DataAccessException hierarchy to hide whether you are using JPA, Hibernate, JDBC, or similar. Actually, it is a hierarchy of sub-exceptions, and not just one exception for everything. It is consistent across all the supported data access technologies. The following diagram depicts the Spring Data Access Exception hierarchy:
  • As you can see in the preceding figure, Spring's DataAccessException extends the RuntimeException, that is, it is an unchecked exception. In an enterprise application, unchecked exceptions can be thrown up the call hierarchy to the best place to handle it. The good thing is that the methods in between don't know about it in the application.

Let's first discuss how to configure Spring with a data source to be able to connect the database, before declaring the templates and repositories in a Spring application.

..................Content has been hidden....................

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