Spring’s Enterprise performance
Data Access Objects (DAO) DAOs exist to provide a means to read and write data to thedatabase. Such functionality is exp...
Spring’s data access exception hierarchy JDBC’s exception hierarchy versus Spring’s data access exceptions:JDBC’s excepti...
Templating Data Access A template method delegates the implementation specificportions of the process to an interface. D...
Spring Data Access TemplatesTemplate class Template used forjca.cci.core.CciTemplate JCA CCI connectionsjdbc.core.JdbcTemp...
DAO support classes Each template also provides convenience methods thatsimplify data access without the need to create a...
The relationship between Application DAOand Spring’s DAO support and templateclassesDAO SupportDatabaseData AccessTemplate...
Spring’s DAO support classesDAO support class (org.springframework.*) Provides DAO support for…jca.cci.support.CciDaoSuppo...
Configuring JNDI Datasource Spring enables to configure a reference to a data source kept inJNDI and wire it into the cla...
JNDI in Spring 2.0 The XML required for retrieving a data source fromJNDI is greatly simplified using the jee namespace....
Connection Pool DataSource Spring doesn’t provide a pooled data source itself but can integrate with JakartaCommons Datab...
Spring JDBC templates Spring’s JDBC framework cleans up the boilerplate JDBC code byshouldering the burden of resource ma...
JdbcTemplate A JdbcTemplate bean is configured in Spring with the following XML: <bean id="jdbcTemplate“ class="org.spri...
Named Parameters The order of the parameters in the query and list of thevalues must be in the correct order when passing...
SimpleJdbcTemplate SimpleJdbcTemplate takes advantage of some of Java 5’ssyntax features. It is configured much like reg...
DAO support classes for JDBC To avoid adding JdbcTemplate property and setter method,then wiring the JdbcTemplate bean in...
Integrating Hibernate with Spring Object-relational Mapping (ORM) services: Lazy loading—In complex object graphs were e...
Hibernate templates The main interface for interacting with Hibernate isorg.hibernate.Session. The Session interface pro...
Classic Hibernate Mapping files LocalSessionFactoryBean is used to work with Hibernate’s classic XMLmapping files. Local...
LocalSessionFactoryBean Spring’s LocalSessionFactoryBean is a factory beanthat loads one or more Hibernate mapping XML fi...
LocalSessionFactoryBean Configuration The dataSource property refers to any implementation ofjavax.sql.DataSource. The m...
Annotated Domain Objects Annotations to tag domain objects can be used with persistencemetadata in Java 5 environment. H...
Accessing data using Hibernate template A DAO Object accepts a HibernateTemplate reference via setterinjection, and confi...
Summary of Hibernate Templates The configuration of DAO Class involves 4 beans. First the data source is wired into the ...
Hibernate-backed DAOs HibernateDaoSupport is a convenience DAO support classwhich enables to wire a session factory bean ...
Hibernate 3 contextual sessions HibernateTemplate is used to manage the Hibernate sessionswhich is somewhat intrusive in ...
Spring Modules caching moduleThe Spring Modules caching module intercepts calls to abean’s methods, looking up data from a...
Configuring Spring with EHCache First a new Spring configuration file is created to declare caching in. The new configur...
Proxying beans for caching The <ehcache:proxy> element wraps the Dao Object with aproxy that caches everything returned f...
Flushing the cache The <ehcache:flushing> element declares methods that empty thecache. <ehcache:flushing methodName="sa...
Declaring a proxied inner bean The <ehcache:proxy>’s id attributes should not give the id of the real Dao bean. To renam...
Upcoming SlideShare
Loading in …5
×

Enterprise Spring

653 views

Published on

Enterprise Spring

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
653
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
12
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Enterprise Spring

  1. 1. Spring’s Enterprise performance
  2. 2. Data Access Objects (DAO) DAOs exist to provide a means to read and write data to thedatabase. Such functionality is exposed through an interface bywhich the rest of the application will access them. It makes your service objects easily testable since they arenot coupled to a specific data access implementation. The chosen persistence approach is isolated to the DAOwhile only the relevant data access methods are exposedthrough the interface. Spring insulates the data access tier from the rest ofapplication by providing a consistent exception hierarchyused across all of its DAO frameworks.
  3. 3. Spring’s data access exception hierarchy JDBC’s exception hierarchy versus Spring’s data access exceptions:JDBC’s exceptions Spring’s data access exceptionsBatchUpdateExceptionDataTruncationSQLExceptionSQLWarningCannotAcquireLockExceptionCannotSerializeTransactionExceptionCleanupFailureDataAccessExceptionConcurrencyFailureExceptionDataAccessException (root of all exceptions, unchecked)DataAccessResourceFailureExceptionDataIntegrityViolationExceptionDataRetrievalFailureExceptionDeadlockLoserDataAccessExceptionEmptyResultDataAccessExceptionIncorrectResultSizeDataAccessExceptionIncorrectUpdateSemanticsDataAccessExceptionInvalidDataAccessApiUsageExceptionInvalidDataAccessResourceUsageExceptionOptimisticLockingFailureExceptionPermissionDeniedDataAccessExceptionPessimisticLockingFailureExceptionTypeMismatchDataAccessExceptionUncategorizedDataAccessException
  4. 4. Templating Data Access A template method delegates the implementation specificportions of the process to an interface. Different implementations of the interface define specificimplementations of the portion of the process. There are the fixed steps in a data access process but eachdata access method is slightly different. Spring separates the fixed and variable parts of the dataaccess process into two distinct classes: templates andcallbacks. Templates manage the fixed part of the process while thecustom data access code is handled in the callbacks.
  5. 5. Spring Data Access TemplatesTemplate class Template used forjca.cci.core.CciTemplate JCA CCI connectionsjdbc.core.JdbcTemplate JDBC connectionsjdbc.core.namedparam.Named-ParameterJdbcTemplateJDBC connections with supportfor named parametersjdbc.core.simple.SimpleJdbcTemplate JDBC connections, simplifiedwith Java 5 constructsorm.hibernate.HibernateTemplate Hibernate 2.x sessionsorm.hibernate3.HibernateTemplate Hibernate 3.x sessionsorm.ibatis.SqlMapClientTemplate iBATIS SqlMap clientsorm.jdo.JdoTemplate Java Data Object implementationsorm.jpa.JpaTemplate Java Persistence API entity Managersorm.toplink.TopLinkTemplate Oracle’s TopLink
  6. 6. DAO support classes Each template also provides convenience methods thatsimplify data access without the need to create an explicitcallback implementation. On top of the template-callback design, Spring providesDAO support classes that are meant to be subclassed bycustom DAO classes. The DAO implementation can subclass a DAO supportclass and call a template retrieval method to have directaccess to the underlying data access template. Each of the DAO support classes provide access to whateverclass it uses to communicate with the database.
  7. 7. The relationship between Application DAOand Spring’s DAO support and templateclassesDAO SupportDatabaseData AccessTemplatePersistenceFrameworkApplicationDAO
  8. 8. Spring’s DAO support classesDAO support class (org.springframework.*) Provides DAO support for…jca.cci.support.CciDaoSupport JCA CCI connectionsjdbc.core.support.JdbcDaoSupport JDBC connectionsjdbc.core.namedparam.NamedParameterJdbcDaoSupportJDBC connections with supportfor named parametersjdbc.core.simple.SimpleJdbcDaoSupport JDBC connections, simplifiedwith Java 5 constructsorm.hibernate.support.HibernateDaoSupport Hibernate 2.x sessionsorm.hibernate3.support.HibernateDaoSupport Hibernate 3.x sessionsorm.ibatis.support.SqlMapClientDaoSupport iBATIS SqlMap clientsorm.jdo.support.JdoDaoSupport Java Data Objectimplementationsorm.jpa.support.JpaDaoSupport JPA entity Managersorm.toplink.support.TopLinkDaoSupport Oracle’s TopLink
  9. 9. Configuring JNDI Datasource Spring enables to configure a reference to a data source kept inJNDI 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 aSpring 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 theresource in JNDI. When resourceRef set to true, the value of jndiName will beprepended with java:comp/env/ to retrieve the data source as aJava resource from the application server’s JNDI directory.
  10. 10. JNDI in Spring 2.0 The XML required for retrieving a data source fromJNDI 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 mapdirectly to the jndiName and resourceRef properties ofJndiObjectFactoryBean.
  11. 11. Connection Pool DataSource Spring doesn’t provide a pooled data source itself but can integrate with JakartaCommons Database Connection Pools (DBCP) which includes several datasources 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 passwordproperties are used to authenticate during connection, initialsize specifies theno of connections in the pool at the start, while maxactive speifies themaximum connections the pool can have. The spring’s JDBC driver has classes DriverManagerDataSource whichreturns new connections everytime requested whileSingleConnectionDataSource returns the same connection every timerequested. Neither of both provide a connection pool.
  12. 12. Spring JDBC templates Spring’s JDBC framework cleans up the boilerplate JDBC code byshouldering the burden of resource management and exceptionhandling. Spring abstracts away the boilerplate data access code behindtemplate 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 andsimple indexed-parameter queries. ■ NamedParameterJdbcTemplate—This JDBC template classenables to perform queries where values are bound to namedparameters in SQL, rather than indexed parameters. ■ SimpleJdbcTemplate—This version of the JDBC templatetakes advantage of Java 5 features such as autoboxing, generics,and variable parameter lists to simplify how a JDBC template isused.
  13. 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 thedatabase. The JdbcTemplate greatly simplifies the DAO methods with no more connection orstatement creation or exception handling code. All the boilerplate code is hidden inside the JdbcTemplate. Internally, JdbcTemplate catches any SQLExceptions that are thrown and then translatesthe generic SQLException into one of the more specific data access runtime exceptionsand 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 domainobject. For every row that results from the query, JdbcTemplate calls the mapRow() method ofthe RowMapper which creates a object and populates it with values from the ResultSet.
  14. 14. Named Parameters The order of the parameters in the query and list of thevalues must be in the correct order when passing themto the update() method. The Named parameters give each parameter in theSQL an explicit name to refer to the parameter whenbinding values to the statement. With named parameter queries, the order of thebound values isn’t important. NamedParameterJdbcTemplate is a special JDBCtemplate which supports named parameters and isn’t asubclass of JdbcTemplate.
  15. 15. SimpleJdbcTemplate SimpleJdbcTemplate takes advantage of some of Java 5’ssyntax features. It is configured much like regular JdbcTemplate bean: <bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> It makes possible to pass variable-length parameter listswithout having to construct an array of Object. It also takes advantage of Java 5’s support for autoboxingwhen mapping result sets. ParameterizedRowMapper is used which takes advantageof Java 5 covariant return types to specify a specific returntype for the mapRow() method
  16. 16. DAO support classes for JDBC To avoid adding JdbcTemplate property and setter method,then wiring the JdbcTemplate bean into the JdbcTemplateproperty for each DAO, a base DAO class is created thatholds the JdbcTemplate. Spring’s JdbcDaoSupport is a base class for writing JDBC-backed DAO classes by extending it. The JdbcDaoSupport provides convenient access to theJdbcTemplate through the getJdbcTemplate() method. When configuring the DAO class in Spring, a JdbcTemplatebean could be directly wired into its jdbcTemplate propertyor a data source could be directly wired into the dataSourceproperty. Spring’s NamedParameterJdbcDaoSupport to use namedparameter in queries instead of indexed parameters. SimpleJdbcDaoSupport is a DAO support class providingJava 5’s advantages such as varargs and autoboxing.
  17. 17. Integrating Hibernate with Spring Object-relational Mapping (ORM) services: Lazy loading—In complex object graphs were entirerelationships needs to be fetched immediately, grabbing dataonly as it is needed. Eager fetching—Eager fetching allows to grab an entire objectgraph in one query. It enables to get the from the database in oneoperation, saving from costly round-trips. Cascading—It enables the changes to a database table to resultin changes to other tables as well. Spring’s support for ORM frameworks provides integrationpoints 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. 18. Hibernate templates The main interface for interacting with Hibernate isorg.hibernate.Session. The Session interface provides basic data access functionality such asability to save, update, delete, and load objects from the database. Hibernate’s SessionFactory interface provides a standard way to get areference to a Hibernate Session object. It is also responsible foropening, closing, and managing Hibernate Sessions. Spring’s HibernateTemplate provides an abstract layer over aHibernate Session. HibernateTemplate simplifies the work of opening and closingHibernate Sessions and to convert Hibernate-specific exceptions to oneof 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 implementationof org.hibernate.SessionFactory
  19. 19. Classic Hibernate Mapping files LocalSessionFactoryBean is used to work with Hibernate’s classic XMLmapping files. LocalSessionFactoryBean is a Spring factory bean that produces a localHibernate SessionFactory instance that draws its mapping metadatafrom 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. 20. LocalSessionFactoryBean Spring’s LocalSessionFactoryBean is a factory beanthat loads one or more Hibernate mapping XML filesto produce a Hibernate SessionFactory.HibernateMappingXMLLocal SessionFactoryBeanHibernateSession Factory
  21. 21. LocalSessionFactoryBean Configuration The dataSource property refers to any implementation ofjavax.sql.DataSource. The mappingResources property takes a list of one ormore paths to mapping files as resources in the classpath. The hibernateProperties property provides anyadditional configuration pertinent to the Hibernatesession. The Hibernate dialect specifies how Hibernate constructsits SQL for a particular database. The dialect decision is left as a placeholder variable that isreplaced by PropertyPlaceholderConfigurer .
  22. 22. Annotated Domain Objects Annotations to tag domain objects can be used with persistencemetadata in Java 5 environment. Hibernate 3 supports both JPA annotations and Hibernate-specific annotations describing how objects are persisted. Spring’s AnnotationSessionFactoryBean is similar toLocalSessionFactoryBean for annotation-based Hibernate,except that it creates a SessionFactory based on annotations inone or more domain classes. The XML required to configure anAnnotationSessionFactoryBean in Spring is similar to the XMLfor LocalSessionFactoryBean. Also instead of configuring one or more mapping files, hereAnnotationSessionFactoryBean is configured with one or moreclasses that are annotated for persistence with Hibernate
  23. 23. Accessing data using Hibernate template A DAO Object accepts a HibernateTemplate reference via setterinjection, 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 toaccess objects stored in the database, such as using thesaveOrUpdate() method of HibernateTemplate to save an Object. The saveOrUpdate() method inspects the object to see if its IDfield is null. If so then it must be a new object and is inserted intothe database else, it is assumed an existing object and its data isupdated. The hibernate find() method is used to retrieve an object byquerying the database and the load() method loads a specificinstance of an Object by the object’s ID field.
  24. 24. Summary of Hibernate Templates The configuration of DAO Class involves 4 beans. First the data source is wired into the session factorybean (either LocalSessionFactoryBean orAnnotationSessionFactoryBean). Then session factory bean is wired into theHibernateTemplate. Finally, the HibernateTemplate is wired into the DAOClass , where it is used to access the database.
  25. 25. Hibernate-backed DAOs HibernateDaoSupport is a convenience DAO support classwhich enables to wire a session factory bean directly into theDAO class. Under the covers, HibernateDaoSupport creates aHibernateTemplate that the DAO can use. The getHibernateTemplate() method of HibernateDaoSupportprovides a HibernateTemplate that is created byHibernateDaoSupport. HibernateDaoSupport requires Hibernate SessionFactory toproduce a HibernateTemplate internally. Hence the sessionFactory bean is wired into the sessionFactoryproperty Of Dao Class: <bean id="rantDao"class="com.roadrantz.dao.hibernate.HibernateRantDao"> <property name="sessionFactory" ref="sessionFactory" /> </bean
  26. 26. Hibernate 3 contextual sessions HibernateTemplate is used to manage the Hibernate sessionswhich is somewhat intrusive in the application code. The Contextual sessions of Hibernate 3 provide a way in whichHibernate itself manages one Session per transaction. HibernateTemplate is no longer needed and HibernateSessionFactory is wired into DAO instead of HibernateTemplate. A SessionFactory reference is injected in sessionFactory property. Since SessionFactory comes from the Hibernate API, the DAO nolonger depends on the Spring Framework. Instead of using HibernateTemplate to perform persistenceoperations, the SessionFactory is used. For example: sessionFactory.getCurrentSession().saveOrUpdate(rant); Hibernate contextual sessions decouple the DAOimplementations from Spring but is coupled with the HibernateORM solution, as they throw Hibernatespecific exceptions.
  27. 27. Spring Modules caching moduleThe Spring Modules caching module intercepts calls to abean’s methods, looking up data from a cache for quick dataaccess and thus avoiding unnecessary slow queries to thedatabase.
  28. 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 enableEHCache 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 withJava 5 annotations. <namespace:commons-attributes>: Declaring cached methods by taggingthem 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 SpringXML. <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 themandatory <defaultCache> element telling the cache to use if no suitable cacheis found and the <cache> element which defines other zero or more times.
  29. 29. Proxying beans for caching The <ehcache:proxy> element wraps the Dao Object with aproxy that caches everything returned from the specifiedmethod: <ehcache:proxy id="rantDao“ refId="rantDaoTarget"> <ehcache:caching methodName="getRantsForDay" cacheName="rantzCache" /> </ehcache:proxy> The <ehcache:caching> element declares which method(s) willbe intercepted and which cache their return values will becached in. <ehcache:caching> can be declared multiple times to describecaching for a bean’s methods. Wildcards can be used to specify multiple methods with onlyone <ehcache:caching> element.
  30. 30. Flushing the cache The <ehcache:flushing> element declares methods that empty thecache. <ehcache:flushing methodName="saveRant“cacheName="rantzCache" /> The cache specified in the cacheName attribute will be flushedafter the method specified with methodName is invoked. But you can change the timing of the flush by using the whenattribute: <ehcache:flushing methodName="saveRant“cacheName="rantzCache" when="before" /> By setting when to before we are asking for the cache to be flushedbefore the specified method is invoked.
  31. 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 refIdattribute. 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

×