Spring Study Notes - Copyright © 2010 Gavin Lasnitzki Index   Notes   Objectives
Spring Data Access and JDBC Support

10. DAO support

Objectives: 3.1 The role of Spring in enterprise data access

10.1. Introduction

Aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way.

10.2. Consistent exception hierarchy Key

Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the (unchecked) DataAccessException as the root exception.
These exceptions wrap the original exception (so no information is lost).

10.3. Consistent abstract classes for DAO support Key Question

Spring provides a set of abstract DAO classes that one can extend.
These templates have methods for providing the data source and any other configuration settings.
These include: JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport, JpaDaoSupport.

11. Data access using JDBC

11.1. Introduction

Objectives: 3.3 Spring data access support

Spring value add is shown by the following, where "Spring" indicates that action is handled by the framework. Key

  1. (Spring) Define connection parameters
  2. (Spring) Open the connection
  3. (Developer) Specify the statement
  4. (Spring) Prepare and execute the statement
  5. (Spring) Set up the loop to iterate through the results (if any)
  6. (Developer) Do the work for each iteration
  7. (Spring) Process any exception
  8. (Spring) Handle transactions
  9. (Spring) Close the connection

11.1.1. Choosing a style

Styles: Question

  • JdbcTemplate (and extended by NamedParameterJdbcTemplate)
    Classic approach.
    Used at the "lowest level" by other approaches.
    Suitable for JDK 1.4+.
  • SimpleJdbc (including SimpleJdbcInsert and SimpleJdbcCall)
    Uses Java 5 features (including generics).
    Has functionality of NamedParameterJdbcTemplate.
  • RDBMS Object
    More object oriented approach similar in style to the JDO Query design.
    Suitable for JDK1.4+

11.1.2. The package hierarchy

  • ...jdbc.core - contains the JdbcTemplate class and its various callback interfaces (including simple and namedparam packages).
  • ...jdbc.datasource - contains the utility classes for easy DataSource access and various simple DataSource implementations.
  • ...jdbc.object - contains the RDBMS queries classes.
  • ...jdbc.support - contains utility classes and the SQLException translation functionality.
  • ...dao - contains the Spring exceptions.

11.2. Using the JDBC Core classes to control basic JDBC processing and error handling

11.2.1. JdbcTemplate Key

Objectives: 3.6 Spring's JdbcTemplate

JdbcTemplate handles: Question

  • Creation and release (like closing connection) of resources.
  • Creation and execution of statements (select, update, insert, stored procedures).
  • Iteration over ResultSet and extracts returns parameter values.
  • Translation of JDBC exceptions into generic, unchecked exceptions.

JdbcTemplate uses callback interfaces to provide a clearly define contract (for executing statements and processing results).
It can be used within a DAO implementation via direct instantiation.
It logs all SQL (at debug level). Examples



Insert: JdbcTemplate idioms (best practices) Key Question

Instances of the JdbcTemplate class are threadsafe once configured.
This means that the JdbcTemplate is stateful, in that it maintains a reference to a DataSource, but this state is not conversational state.

Common practice is to create the template in the setter for the DataSource (as in the Spring DaoSupport classes).

Use multiple templates when using multiple DataSources (which is the case when accessing multiple databases). Question

11.2.2. NamedParameterJdbcTemplate

The NamedParameterJdbcTemplate class adds support for programming JDBC statements using named parameters (as opposed to programming JDBC statements using only classic placeholder ('?') arguments.
The the SqlParameterSource interface allows parameters to be retrieved from different sources (MapSqlParameterSource - from a map, BeanPropertySqlParameterSource - from a bean)

11.2.3. SimpleJdbcTemplate

The SimpleJdbcTemplate class is a wrapper around the classic JdbcTemplate that takes advantage of Java 5 language features such as generics, varargs and autoboxing. Question

Use getJdbcOperations() to access the JdbcTemplate from the SimpleJdbcTemplate.

11.2.4. DataSource

The DataSource allows a container or a framework to hide connection pooling and transaction management issues from the application code.

The DriverManagerDataSource is configured in a similar manner to the standard JDBC connection.

11.2.5. SQLExceptionTranslator

SQLExceptionTranslator is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic org.springframework.dao.DataAccessException.

SQLErrorCodeSQLExceptionTranslator is the implementation of SQLExceptionTranslator that is used by default. This uses vendor specific codes for a more precise translation.

11.2.6. Executing statements

11.2.7. Running Queries Key

Includes: queryForInt(..), queryForLong(..), queryForObject(..) and queryForList(..)

11.2.8. Updating the database

11.2.9. Retrieving auto-generated keys

11.3. Controlling database connections


11.3.1. DataSourceUtils

This is a powerful helper class that provides static methods to obtain connections from JNDI and close connections if necessary.

11.3.2. SmartDataSource

Allows you to query whether or not the connection should be closed after a given operation.

11.3.3. AbstractDataSource

11.3.4. SingleConnectionDataSource

Implementation of the SmartDataSource interface that wraps a single Connection that is not closed after use.
This is primarily a test class.

11.3.5. DriverManagerDataSource

Implementation of the standard DataSource interface that configures a plain old JDBC Driver via bean properties, and returns a new Connection every time.

11.3.6. TransactionAwareDataSourceProxy

11.3.7. DataSourceTransactionManager

PlatformTransactionManager implementation for single JDBC datasources.
It binds a JDBC connection from the specified data source to the currently executing thread, potentially allowing for one thread connection per data source.
It class supports custom isolation levels and timeouts.

11.3.8. NativeJdbcExtractor

Extracts the underlying vendor specific connection.

11.4. JDBC batch operations

Improved performance if you batch multiple calls to the same prepared statement.

11.4.1. Batch operations with the JdbcTemplate

For the JdbcTemplate, call the batchUpdate method and pass in a BatchPreparedStatementSetter implementation.

11.4.2. Batch operations with the SimpleJdbcTemplate

11.5. Simplifying JDBC operations with the SimpleJdbc classes

11.5.1. Inserting data using SimpleJdbcInsert

11.5.2. Retrieving auto-generated keys using SimpleJdbcInsert

11.5.3. Specifying the columns to use for a SimpleJdbcInsert

11.5.4. Using SqlParameterSource to provide parameter values

11.5.5. Calling a stored procedure using SimpleJdbcCall

11.5.6. Declaring parameters to use for a SimpleJdbcCall

11.5.7. How to define SqlParameters

11.5.8. Calling a stored function using SimpleJdbcCall

11.5.9. Returning ResultSet/REF Cursor from a SimpleJdbcCall

11.6. Modeling JDBC operations as Java objects

11.6.1. SqlQuery

11.6.2. MappingSqlQuery

11.6.3. SqlUpdate

11.6.4. StoredProcedure

11.6.5. SqlFunction

11.7. Common issues with parameter and data value handling

11.7.1. Providing SQL type information for parameters

11.7.2. Handling BLOB and CLOB objects

11.7.3. Passing in lists of values for IN clause

11.7.4. Handling complex types for stored procedure calls

12. Object Relational Mapping (ORM) data access Key

12.1. Introduction

Objectives: 3.7 ORM Fundamentals , 3.8 Benefits of O/R Mapping

The Spring Framework provides integration in terms of resource management, DAO implementation support, and transaction strategies.

Coding styles: styles: Spring's DAO 'templates' or coding DAOs against vendors APIs.

Benefits of using the Spring Framework

  • Ease of testing - IoC makes it easy to switch implementations and config locations.
  • Common data access exceptions - Converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy.
  • General resource management - Easy configuration (i.e. Hibernate's SessionFactory).

Integrated transaction management - Spring allows you to wrap your O/R mapping code with either a declarative, AOP style method interceptor, or an explicit 'template' wrapper class at the Java code level.
Allows JDBC-related code integrate transactionally with the O/R mapping code.

12.2. Hibernate

Objectives: 3.9 Hibernate General


12.2.1. Resource management

Objectives: 3.2 Spring resource management

Support consisting of a HibernateTemplate.

12.2.2. SessionFactory setup in a Spring container Key

Spring allows you to define resources such as a JDBC DataSource or a Hibernate SessionFactory as beans in the container.


12.2.3. The HibernateTemplate Key

Objectives: 3.10 Spring's HibernateTemplate

Provides many methods that mirror the methods exposed on the Hibernate Session interface.

Use the HibernateCallback() to access the underlying Session.

The template instances are thread-safe and reusable.

Spring provides a convenient HibernateDaoSupport base class to access the SessionFactory and HibernateTemplate.

12.2.4. Implementing Spring-based DAOs without callbacks

Use the the SessionFactoryUtils class to convert exceptions to the DataAccessException hierarchy.

12.2.5. Implementing DAOs based on plain Hibernate 3 API

12.2.6. Programmatic transaction demarcation

12.2.7. Declarative transaction demarcation

12.2.8. Transaction management strategies

12.2.9. Container resources versus local resources

12.2.10. Spurious application server warnings when using Hibernate

12.3. JDO

Excluded from Exam

12.3.1. PersistenceManagerFactory setup

12.3.2. JdoTemplate and JdoDaoSupport

12.3.3. Implementing DAOs based on the plain JDO API

12.3.4. Transaction management

12.3.5. JdoDialect

12.4. Oracle TopLink

Excluded from Exam

12.4.1. SessionFactory abstraction

12.4.2. TopLinkTemplate and TopLinkDaoSupport

12.4.3. Implementing DAOs based on plain TopLink API

12.4.4. Transaction management

12.5. iBATIS SQL Maps

Excluded from Exam

12.5.1. Setting up the SqlMapClient

12.5.2. Using SqlMapClientTemplate and SqlMapClientDaoSupport

12.5.3. Implementing DAOs based on plain iBATIS API

12.6. JPA

Excluded from Exam

12.6.1. JPA setup in a Spring environment LocalEntityManagerFactoryBean Obtaining an EntityManagerFactory from JNDI LocalContainerEntityManagerFactoryBean Dealing with multiple persistence units

12.6.2. JpaTemplate and JpaDaoSupport

12.6.3. Implementing DAOs based on plain JPA

12.6.4. Exception Translation

12.7. Transaction Management

Excluded from Exam

12.8. JpaDialect

Excluded from Exam