errorTranslator.setDataSource(dataSource);
jdbcTemplate.setExceptionTranslator(errorTranslator);
// use the JdbcTemplate for this SqlUpdate
SqlUpdate sqlUpdate = new SqlUpdate();
sqlUpdate.setJdbcTemplate(jdbcTemplate);
sqlUpdate.setSql("update contact set first_name = 'Clarence'");
sqlUpdate.compile();
sqlUpdate.update();
Having the custom SQL exception translator in place, Spring will invoke it upon SQL exceptions
detected when executing SQL statements against the database, and custom exception translation will
happen when the error code is -12345. For other errors, Spring will fall back to its default mechanism for
exception translation.
Obviously, nothing can stop you from creating the SQLExceptionTranslator as a Spring-managed
bean and using the JdbcTemplate bean in your DAO classes. Don't worry if you don't remember reading
about the JdbcTemplate class; we are going to discuss it in more detail.
The JdbcTemplate Class
This class represents the core of Spring's JDBC support. It can execute all types of SQL statements. In the
most simplistic view, you can classify the data definition and data manipulation statements. Data
definition statements cover creating various database objects (tables, views, stored procedures, and so
on). Data manipulation statements manipulate the data and can be classified as select and update
statements. A select statement generally returns a set of rows; each row has the same set of columns. An
update statement modifies the data in the database but does not return any results.
The JdbcTemplate class allows you to issue any type of SQL statement to the database and return any
type of result.
In this section, we will go through several common use cases for JDBC programming in Spring with
the JdbcTemplate class.
Initializing JdbcTemplate in a DAO Class
Before we discuss how to use JdbcTemplate, let's take a look at how to prepare JdbcTemplate for use in
the DAO class. It's very straightforward; most of the time you just need to construct the class by passing
in the data source object (which should be injected by Spring into the DAO class). Listing 8-23 shows the
code snippet that will initialize the JdbcTemplate object.
Listing 8-23. Initialize JdbcTemplate
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
The general practice is to initialize the JdbcTemplate within the set data source method so that once
the data source was injected by Spring, the JdbcTemplate will also be initialized and ready for use.
Once configured, the JdbcTemplate is thread safe. That means you can also choose to initialize a
single instance of JdbcTemplate in Spring's XML configuration and have it inject into all DAO beans.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home