SlideShare une entreprise Scribd logo
1  sur  31
Spring’s Enterprise performance
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.
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
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.
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
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.
The relationship between Application DAO
and Spring’s DAO support and template
classes
DAO Support
Database
Data Access
Template
Persistence
Framework
Application
DAO
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
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.
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.
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.
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.
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.
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.
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
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.
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
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
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>
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
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 .
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
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.
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.
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
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.
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.
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.
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.
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.
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

Contenu connexe

Tendances

Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginersAmbarish Rai
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5phanleson
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to adoHarman Bajwa
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 

Tendances (20)

Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Ado.net
Ado.netAdo.net
Ado.net
 
Hibernate
HibernateHibernate
Hibernate
 
Jdbc slide for beginers
Jdbc slide for beginersJdbc slide for beginers
Jdbc slide for beginers
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
Jdbc
JdbcJdbc
Jdbc
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 

Similaire à Enterprise Spring

Similaire à Enterprise Spring (20)

Spring jdbc dao
Spring jdbc daoSpring jdbc dao
Spring jdbc dao
 
Spring framework DAO
Spring framework  DAOSpring framework  DAO
Spring framework DAO
 
Spring database - part2
Spring database -  part2Spring database -  part2
Spring database - part2
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Mule jdbc
Mule   jdbcMule   jdbc
Mule jdbc
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
JDBC
JDBCJDBC
JDBC
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
Data access
Data accessData access
Data access
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Java Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptxJava Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptx
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 

Plus de Emprovise

Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)Emprovise
 
Leadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/BusinessLeadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/BusinessEmprovise
 
Secure socket layer
Secure socket layerSecure socket layer
Secure socket layerEmprovise
 
Effective java
Effective javaEffective java
Effective javaEmprovise
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance FeaturesEmprovise
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEmprovise
 
RESTful WebServices
RESTful WebServicesRESTful WebServices
RESTful WebServicesEmprovise
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE PatternsEmprovise
 
Spring Web Services
Spring Web ServicesSpring Web Services
Spring Web ServicesEmprovise
 
Spring Web Webflow
Spring Web WebflowSpring Web Webflow
Spring Web WebflowEmprovise
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web ViewsEmprovise
 
Spring Basics
Spring BasicsSpring Basics
Spring BasicsEmprovise
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 AdvanceEmprovise
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 FrameworkEmprovise
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance ConceptsEmprovise
 

Plus de Emprovise (20)

Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
 
Leadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/BusinessLeadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/Business
 
Secure socket layer
Secure socket layerSecure socket layer
Secure socket layer
 
Effective java
Effective javaEffective java
Effective java
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance Features
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business Logic
 
EJB3 Basics
EJB3 BasicsEJB3 Basics
EJB3 Basics
 
RESTful WebServices
RESTful WebServicesRESTful WebServices
RESTful WebServices
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE Patterns
 
Spring JMS
Spring JMSSpring JMS
Spring JMS
 
JMS
JMSJMS
JMS
 
Spring Web Services
Spring Web ServicesSpring Web Services
Spring Web Services
 
Spring Web Webflow
Spring Web WebflowSpring Web Webflow
Spring Web Webflow
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web Views
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 Advance
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 Framework
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
 

Dernier

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 

Dernier (20)

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 

Enterprise Spring

  • 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