2. Data Access Objects (DAO)
DAOs exist to provide a means to read and write data to the
database.
Such functionality is exposed through an interface by
which the rest of the application will access them.
It makes your service objects easily testable since they are
not coupled to a specific data access implementation.
The chosen persistence approach is isolated to the DAO
while only the relevant data access methods are exposed
through the interface.
Spring insulates the data access tier from the rest of
application by providing a consistent exception hierarchy
used across all of its DAO frameworks.
3. Spring’s data access exception hierarchy
JDBC’s exception hierarchy versus Spring’s data access exceptions:
JDBC’s exceptions Spring’s data access exceptions
BatchUpdateException
DataTruncation
SQLException
SQLWarning
CannotAcquireLockException
CannotSerializeTransactionException
CleanupFailureDataAccessException
ConcurrencyFailureException
DataAccessException (root of all exceptions, unchecked)
DataAccessResourceFailureException
DataIntegrityViolationException
DataRetrievalFailureException
DeadlockLoserDataAccessException
EmptyResultDataAccessException
IncorrectResultSizeDataAccessException
IncorrectUpdateSemanticsDataAccessException
InvalidDataAccessApiUsageException
InvalidDataAccessResourceUsageException
OptimisticLockingFailureException
PermissionDeniedDataAccessException
PessimisticLockingFailureException
TypeMismatchDataAccessException
UncategorizedDataAccessException
4. Templating Data Access
A template method delegates the implementation specific
portions of the process to an interface.
Different implementations of the interface define specific
implementations of the portion of the process.
There are the fixed steps in a data access process but each
data access method is slightly different.
Spring separates the fixed and variable parts of the data
access process into two distinct classes: templates and
callbacks.
Templates manage the fixed part of the process while the
custom data access code is handled in the callbacks.
5. Spring Data Access Templates
Template class Template used for
jca.cci.core.CciTemplate JCA CCI connections
jdbc.core.JdbcTemplate JDBC connections
jdbc.core.namedparam.Named-
ParameterJdbcTemplate
JDBC connections with support
for named parameters
jdbc.core.simple.SimpleJdbcTemplate JDBC connections, simplified
with Java 5 constructs
orm.hibernate.HibernateTemplate Hibernate 2.x sessions
orm.hibernate3.HibernateTemplate Hibernate 3.x sessions
orm.ibatis.SqlMapClientTemplate iBATIS SqlMap clients
orm.jdo.JdoTemplate Java Data Object implementations
orm.jpa.JpaTemplate Java Persistence API entity Managers
orm.toplink.TopLinkTemplate Oracle’s TopLink
6. DAO support classes
Each template also provides convenience methods that
simplify data access without the need to create an explicit
callback implementation.
On top of the template-callback design, Spring provides
DAO support classes that are meant to be subclassed by
custom DAO classes.
The DAO implementation can subclass a DAO support
class and call a template retrieval method to have direct
access to the underlying data access template.
Each of the DAO support classes provide access to whatever
class it uses to communicate with the database.
7. The relationship between Application DAO
and Spring’s DAO support and template
classes
DAO Support
Database
Data Access
Template
Persistence
Framework
Application
DAO
8. Spring’s DAO support classes
DAO support class (org.springframework.*) Provides DAO support for…
jca.cci.support.CciDaoSupport JCA CCI connections
jdbc.core.support.JdbcDaoSupport JDBC connections
jdbc.core.namedparam.NamedParameterJdbcD
aoSupport
JDBC connections with support
for named parameters
jdbc.core.simple.SimpleJdbcDaoSupport JDBC connections, simplified
with Java 5 constructs
orm.hibernate.support.HibernateDaoSupport Hibernate 2.x sessions
orm.hibernate3.support.HibernateDaoSupport Hibernate 3.x sessions
orm.ibatis.support.SqlMapClientDaoSupport iBATIS SqlMap clients
orm.jdo.support.JdoDaoSupport Java Data Object
implementations
orm.jpa.support.JpaDaoSupport JPA entity Managers
orm.toplink.support.TopLinkDaoSupport Oracle’s TopLink
9. Configuring JNDI Datasource
Spring enables to configure a reference to a data source kept in
JNDI and wire it into the classes just like another Spring bean.
Spring’s JndiObjectFactoryBean enables to retrieve any object,
including data sources, from JNDI and make it available as a
Spring bean.
JndiObjectFactoryBean retrieving a data source from JNDI as foll:
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean"
scope="singleton">
<property name="jndiName" value="/jdbc/RantzDatasource" />
<property name="resourceRef" value="true" />
</bean>
The jndiName attribute is used to specify the name of the
resource in JNDI.
When resourceRef set to true, the value of jndiName will be
prepended with java:comp/env/ to retrieve the data source as a
Java resource from the application server’s JNDI directory.
10. JNDI in Spring 2.0
The XML required for retrieving a data source from
JNDI is greatly simplified using the jee namespace.
The jee namespace offers the <jee:jndi-lookup>
element for retrieving objects from JNDI.
<jee:jndi-lookup id="dataSource"
jndi-name="/jdbc/RantzDatasource"
resource-ref="true" />
The jndi-name and resource-ref attributes map
directly to the jndiName and resourceRef properties of
JndiObjectFactoryBean.
11. Connection Pool DataSource
Spring doesn’t provide a pooled data source itself but can integrate with Jakarta
Commons Database Connection Pools (DBCP) which includes several data
sources that provide pooling, such as the BasicDataSource.
Sample BasicDataSource configuration is as follows:
<bean id=“mdata” class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url“ value="jdbc:hsqldb:hsql://localhost/roadrantz" />
<property name="username" value="sa" />
<property name="password" value="" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
First four properties are elemental to configuring a BasicDataSource.
The url property specifies the JDBC URL, the username and password
properties are used to authenticate during connection, initialsize specifies the
no of connections in the pool at the start, while maxactive speifies the
maximum connections the pool can have.
The spring’s JDBC driver has classes DriverManagerDataSource which
returns new connections everytime requested while
SingleConnectionDataSource returns the same connection every time
requested. Neither of both provide a connection pool.
12. Spring JDBC templates
Spring’s JDBC framework cleans up the boilerplate JDBC code by
shouldering the burden of resource management and exception
handling.
Spring abstracts away the boilerplate data access code behind
template classes.
For JDBC, Spring comes with three template classes:
■ JdbcTemplate—The most basic of Spring’s JDBC templates,
which provides simple access to a database through JDBC and
simple indexed-parameter queries.
■ NamedParameterJdbcTemplate—This JDBC template class
enables to perform queries where values are bound to named
parameters in SQL, rather than indexed parameters.
■ SimpleJdbcTemplate—This version of the JDBC template
takes advantage of Java 5 features such as autoboxing, generics,
and variable parameter lists to simplify how a JDBC template is
used.
13. JdbcTemplate
A JdbcTemplate bean is configured in Spring with the following XML:
<bean id="jdbcTemplate“ class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
The JdbcTemplate is wired in the DAO using Dependency Injection and used to access the
database.
The JdbcTemplate greatly simplifies the DAO methods with no more connection or
statement creation or exception handling code.
All the boilerplate code is hidden inside the JdbcTemplate.
Internally, JdbcTemplate catches any SQLExceptions that are thrown and then translates
the generic SQLException into one of the more specific data access runtime exceptions
and rethrows it.
Reading data is also simplified with JdbcTemplate using the query method.
The query() method takes three parameters:
■ A String containing the SQL to be used to select the data from the database
■ An array of Object that contains values to be bound to indexed parameters of the query
■ A RowMapper object that extracts values from a ResultSet and constructs a domain
object.
For every row that results from the query, JdbcTemplate calls the mapRow() method of
the RowMapper which creates a object and populates it with values from the ResultSet.
14. Named Parameters
The order of the parameters in the query and list of the
values must be in the correct order when passing them
to the update() method.
The Named parameters give each parameter in the
SQL an explicit name to refer to the parameter when
binding values to the statement.
With named parameter queries, the order of the
bound values isn’t important.
NamedParameterJdbcTemplate is a special JDBC
template which supports named parameters and isn’t a
subclass of JdbcTemplate.
15. SimpleJdbcTemplate
SimpleJdbcTemplate takes advantage of some of Java 5’s
syntax features.
It is configured much like regular JdbcTemplate bean:
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.simple.SimpleJdbcTe
mplate">
<property name="dataSource" ref="dataSource" />
</bean>
It makes possible to pass variable-length parameter lists
without having to construct an array of Object.
It also takes advantage of Java 5’s support for autoboxing
when mapping result sets.
ParameterizedRowMapper is used which takes advantage
of Java 5 covariant return types to specify a specific return
type for the mapRow() method
16. DAO support classes for JDBC
To avoid adding JdbcTemplate property and setter method,
then wiring the JdbcTemplate bean into the JdbcTemplate
property for each DAO, a base DAO class is created that
holds the JdbcTemplate.
Spring’s JdbcDaoSupport is a base class for writing JDBC-
backed DAO classes by extending it.
The JdbcDaoSupport provides convenient access to the
JdbcTemplate through the getJdbcTemplate() method.
When configuring the DAO class in Spring, a JdbcTemplate
bean could be directly wired into its jdbcTemplate property
or a data source could be directly wired into the dataSource
property.
Spring’s NamedParameterJdbcDaoSupport to use named
parameter in queries instead of indexed parameters.
SimpleJdbcDaoSupport is a DAO support class providing
Java 5’s advantages such as varargs and autoboxing.
17. Integrating Hibernate with Spring
Object-relational Mapping (ORM) services:
Lazy loading—In complex object graphs were entire
relationships needs to be fetched immediately, grabbing data
only as it is needed.
Eager fetching—Eager fetching allows to grab an entire object
graph in one query. It enables to get the from the database in one
operation, saving from costly round-trips.
Cascading—It enables the changes to a database table to result
in changes to other tables as well.
Spring’s support for ORM frameworks provides integration
points to the frameworks as well as some additional services:
■ Integrated support for Spring declarative transactions
■ Transparent exception handling
■ Thread-safe, lightweight template classes
■ DAO support classes
■ Resource management
18. Hibernate templates
The main interface for interacting with Hibernate is
org.hibernate.Session.
The Session interface provides basic data access functionality such as
ability to save, update, delete, and load objects from the database.
Hibernate’s SessionFactory interface provides a standard way to get a
reference to a Hibernate Session object. It is also responsible for
opening, closing, and managing Hibernate Sessions.
Spring’s HibernateTemplate provides an abstract layer over a
Hibernate Session.
HibernateTemplate simplifies the work of opening and closing
Hibernate Sessions and to convert Hibernate-specific exceptions to one
of the Spring ORM exceptions.
HibernateTemplate in Spring is configured as follows:
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
The sessionFactory property takes a reference to an implementation
of org.hibernate.SessionFactory
19. Classic Hibernate Mapping files
LocalSessionFactoryBean is used to work with Hibernate’s classic XML
mapping files.
LocalSessionFactoryBean is a Spring factory bean that produces a local
Hibernate SessionFactory instance that draws its mapping metadata
from one or more XML mapping files.
LocalSessionFactoryBean is configured as follows:
<bean id="sessionFactory“
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list> <value>com/roadrantz/domain/Rant.hbm.xml</value> </list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
20. LocalSessionFactoryBean
Spring’s LocalSessionFactoryBean is a factory bean
that loads one or more Hibernate mapping XML files
to produce a Hibernate SessionFactory.
Hibernate
Mapping
XML
Local Session
FactoryBean
Hibernate
Session Factory
21. LocalSessionFactoryBean Configuration
The dataSource property refers to any implementation of
javax.sql.DataSource.
The mappingResources property takes a list of one or
more paths to mapping files as resources in the classpath.
The hibernateProperties property provides any
additional configuration pertinent to the Hibernate
session.
The Hibernate dialect specifies how Hibernate constructs
its SQL for a particular database.
The dialect decision is left as a placeholder variable that is
replaced by PropertyPlaceholderConfigurer .
22. Annotated Domain Objects
Annotations to tag domain objects can be used with persistence
metadata in Java 5 environment.
Hibernate 3 supports both JPA annotations and Hibernate-
specific annotations describing how objects are persisted.
Spring’s AnnotationSessionFactoryBean is similar to
LocalSessionFactoryBean for annotation-based Hibernate,
except that it creates a SessionFactory based on annotations in
one or more domain classes.
The XML required to configure an
AnnotationSessionFactoryBean in Spring is similar to the XML
for LocalSessionFactoryBean.
Also instead of configuring one or more mapping files, here
AnnotationSessionFactoryBean is configured with one or more
classes that are annotated for persistence with Hibernate
23. Accessing data using Hibernate template
A DAO Object accepts a HibernateTemplate reference via setter
injection, and configured in Spring as follows:
<bean id="rantDao"
class="com.roadrantz.dao.hibernate.HibernateRantDao">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
Now the DAO Object can use the injected HibernateTemplate to
access objects stored in the database, such as using the
saveOrUpdate() method of HibernateTemplate to save an Object.
The saveOrUpdate() method inspects the object to see if its ID
field is null. If so then it must be a new object and is inserted into
the database else, it is assumed an existing object and its data is
updated.
The hibernate find() method is used to retrieve an object by
querying the database and the load() method loads a specific
instance of an Object by the object’s ID field.
24. Summary of Hibernate Templates
The configuration of DAO Class involves 4 beans.
First the data source is wired into the session factory
bean (either LocalSessionFactoryBean or
AnnotationSessionFactoryBean).
Then session factory bean is wired into the
HibernateTemplate.
Finally, the HibernateTemplate is wired into the DAO
Class , where it is used to access the database.
25. Hibernate-backed DAOs
HibernateDaoSupport is a convenience DAO support class
which enables to wire a session factory bean directly into the
DAO class.
Under the covers, HibernateDaoSupport creates a
HibernateTemplate that the DAO can use.
The getHibernateTemplate() method of HibernateDaoSupport
provides a HibernateTemplate that is created by
HibernateDaoSupport.
HibernateDaoSupport requires Hibernate SessionFactory to
produce a HibernateTemplate internally.
Hence the sessionFactory bean is wired into the sessionFactory
property
Of Dao Class:
<bean id="rantDao"
class="com.roadrantz.dao.hibernate.HibernateRantDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean
26. Hibernate 3 contextual sessions
HibernateTemplate is used to manage the Hibernate sessions
which is somewhat intrusive in the application code.
The Contextual sessions of Hibernate 3 provide a way in which
Hibernate itself manages one Session per transaction.
HibernateTemplate is no longer needed and Hibernate
SessionFactory is wired into DAO instead of HibernateTemplate.
A SessionFactory reference is injected in sessionFactory property.
Since SessionFactory comes from the Hibernate API, the DAO no
longer depends on the Spring Framework.
Instead of using HibernateTemplate to perform persistence
operations, the SessionFactory is used. For example:
sessionFactory.getCurrentSession().saveOrUpdate(rant);
Hibernate contextual sessions decouple the DAO
implementations from Spring but is coupled with the Hibernate
ORM solution, as they throw Hibernatespecific exceptions.
27. Spring Modules caching module
The Spring Modules caching module intercepts calls to a
bean’s methods, looking up data from a cache for quick data
access and thus avoiding unnecessary slow queries to the
database.
28. Configuring Spring with EHCache
First a new Spring configuration file is created to declare caching in.
The new configuration file is rooted with the <beans> element and to enable
EHCache support ehcache namespace is added:
<beans xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
xsi:schemaLocation="http://www.springmodules.org/schema/ehcache
http://www.springmodules.org/schema/cache/
➥ springmodules-ehcache.xsd"> ……………………..
</beans>
Spring Modules’ configuration elements for configuring declarative caching:
<namespace:annotations>: Declares cached methods by tagging them with
Java 5 annotations.
<namespace:commons-attributes>: Declaring cached methods by tagging
them with Jakarta Commons Attributes metadata.
<namespace:config>: Configuring the EHCache cache provider in Spring XML.
<namespace:proxy>: Declaring cached methods by declaring a proxy in Spring
XML.
<ehcache:config> element tells Spring to find the EHCache configuration file.
<ehcache:config configLocation="classpath:ehcache.xml" />
The EHCache is configured using the ehcache.xml which contains the
mandatory <defaultCache> element telling the cache to use if no suitable cache
is found and the <cache> element which defines other zero or more times.
29. Proxying beans for caching
The <ehcache:proxy> element wraps the Dao Object with a
proxy that caches everything returned from the specified
method:
<ehcache:proxy id="rantDao“ refId="rantDaoTarget">
<ehcache:caching methodName="getRantsForDay"
cacheName="rantzCache" />
</ehcache:proxy>
The <ehcache:caching> element declares which method(s) will
be intercepted and which cache their return values will be
cached in.
<ehcache:caching> can be declared multiple times to describe
caching for a bean’s methods.
Wildcards can be used to specify multiple methods with only
one <ehcache:caching> element.
30. Flushing the cache
The <ehcache:flushing> element declares methods that empty the
cache.
<ehcache:flushing methodName="saveRant“
cacheName="rantzCache" />
The cache specified in the cacheName attribute will be flushed
after the method specified with methodName is invoked.
But you can change the timing of the flush by using the when
attribute:
<ehcache:flushing methodName="saveRant“
cacheName="rantzCache"
when="before" />
By setting when to before we are asking for the cache to be flushed
before the specified method is invoked.
31. Declaring a proxied inner bean
The <ehcache:proxy>’s id attributes should not give the id of the real Dao bean.
To rename the real bean to DaoTarget, which is referred to by the refId
attribute.
If the id/refId arrangement seems awkward, then you also have the option of
declaring the target bean as an inner bean of <ehcache:proxy>. For example,
here’s <ehcache:proxy> reconfigured with HibernateRantDao as an inner bean:
<ehcache:proxy id="rantDao">
<bean class="com.roadrantz.dao.HibernateRantDao">
<property name="sessionFactory"
ref="sessionFactory" />
</bean>
<ehcache:caching
methodName="getRantsForDay"
cacheName="rantzCache" />
</ehcache:proxy>
Eve