Database Access Using the Spring Framework
What this presentation will be  Brief overview of wiring applications using Spring  Using Spring’s JDBC framework  Spring’s transaction support
What this presentation will not cover  In-depth coverage of Spring  Creating web applications using Spring
Overview of wiring with Spring  Discuss…
Concerns when accessing database  Managing transactions  Managing resources  Connection pooling  Cleaning up resources
Some typical JDBC code Code Example
The problem with traditional JDBC code  It’s redundant  It repeats itself quite a bit  The exact same code appears in lots of places  You find yourself doing the same things over and over again  It’s redundant
The problem with redundant code  Violates the DRY principle  Maintenance nightmare since JDBC code is inherently messy  JDBC code is critical, so it is important to get it right, once
Spring’s solution – The Template Pattern  Template Pattern – “Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.”  Uses “callbacks” for implementation specific tasks
So what do this mean in a JDBC context? DAO Template Your code 1. Prepare Resources 3. Execute Statement 2. Start Transaction 5. Commit/Rollback 4. Execute Statement 6. Clean up resource 7. Handle exceptions
But before we get too far ahead… …let’s see how we  Obtain/create a DataSource  Wire a DataSource to our XxxDao classes
Working with DataSources Getting a DataSource from JNDI <bean id=“dataSource” class=“org.springframework.jndi.JndiObjectFactoryBean”> <property name=“jndiName” value=“java:comp/env/jdbc/MyDataSourceName”/> </bean>
Working with DataSources Creating a connection pool <bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource”> <property name="url“ value=“jdbc:mysql://localhost/demo”/>> <property name="driverClassName“ value=“com.mysql.jdbc.Driver”/> <property name="username” value=“test”/> <property name=“password” value=“password”/> </bean>
Working with DataSources Code Example
Overview of Spring JDBC features  As mentioned, provides framework so that Spring manages:  Resources  Transactions  Exceptions  Consistent exception hierarchy  Subclass RuntimeException  Specific and meaningful (no vendor error codes!)  Extensable
Some Spring JDBC callback interfaces  PreparedStatementCreator  Has one method – createPreparedStatement(Connection)  Responsible for creating a PreparedStatement  Does not need to handle SQLExceptions
Some Spring JDBC callback interfaces  SQLProvider  Has one method – getSql()  Typically implemented by PreparedStatementCreator implementers  Useful for debugging
Some Spring JDBC callback interfaces  RowCallbackHandler  Has one method – processRow(ResultSet)  Called for each row in ResultSet  Typically stateful
Some Spring JDBC callback interfaces  RowMapper  Has one method – mapRow(ResultSet rs, int rowNum)  Maps a single row to an Object
Using JdbcTemplate  Central class for Spring JDBC framework  Uses callbacks “under the covers”  All you will need for most JDBC operations
Using JdbcTemplate Code Example
Spring Incrementers  Used to increment primary key value for newly persisted object  Implements DataFieldMaxValueIncrementer  Supports  Oracle sequences  DB2 sequences  PostgreSQL sequences  MySQL for non-auto-increment columns
Using JdbcTemplate Code Example
Hibernate intro  Open source ORM tool  Very mature (version 3.2 on horizon)  Feature-complete  Caching  Eager-fetching  Lazy-loading  Proxying
Using Hibernate  Configure classes to be mapped through  Manually created configuration files  XDoclet generated configuration files  Annotations (JPA and Hibernate)  Configure global properties through hibernate.properties file  Hibernate class analogies  DataSource : SessionFactory  Connection : Session
Using Spring with Hibernate  Use Spring to configure Hibernate  Configure Hibernate mappings  Configure Hibernate properties  Wire dependant object to SessionFactory  Use HibernateTemplate as abstraction to Hibernate API  Manages obtaining Session from SessionFactory  Handles/converts exceptions  Manages transactions
Using JdbcTemplate Code Example
Spring Transaction Management  Supports programmatic (yuck!) and declarative (yeah!) transactions  Declarative transaction management achieved via Spring’s AOP  Declarative transactions can be defined in Spring configuration file or in annotations  Supports many transaction properties  Propagation  Isolation level  Rollback conditions
Spring Proxy Overview depends on SomeClient DaoInterface is wired delegates ProxyBean DaoImpl
Using JdbcTemplate Code Example
Coming in Spring 2.0  Support for AspectJ pointcut language  JPA support?  SimpleJdbcTemplate  Support generics  Support variable argument methods

Spring db-access mod03

  • 1.
    Database Access Usingthe Spring Framework
  • 2.
    What this presentationwill be  Brief overview of wiring applications using Spring  Using Spring’s JDBC framework  Spring’s transaction support
  • 3.
    What this presentationwill not cover  In-depth coverage of Spring  Creating web applications using Spring
  • 4.
    Overview of wiringwith Spring  Discuss…
  • 5.
    Concerns when accessingdatabase  Managing transactions  Managing resources  Connection pooling  Cleaning up resources
  • 6.
    Some typical JDBCcode Code Example
  • 7.
    The problem withtraditional JDBC code  It’s redundant  It repeats itself quite a bit  The exact same code appears in lots of places  You find yourself doing the same things over and over again  It’s redundant
  • 8.
    The problem withredundant code  Violates the DRY principle  Maintenance nightmare since JDBC code is inherently messy  JDBC code is critical, so it is important to get it right, once
  • 9.
    Spring’s solution –The Template Pattern  Template Pattern – “Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.”  Uses “callbacks” for implementation specific tasks
  • 10.
    So what dothis mean in a JDBC context? DAO Template Your code 1. Prepare Resources 3. Execute Statement 2. Start Transaction 5. Commit/Rollback 4. Execute Statement 6. Clean up resource 7. Handle exceptions
  • 11.
    But before weget too far ahead… …let’s see how we  Obtain/create a DataSource  Wire a DataSource to our XxxDao classes
  • 12.
    Working with DataSources Gettinga DataSource from JNDI <bean id=“dataSource” class=“org.springframework.jndi.JndiObjectFactoryBean”> <property name=“jndiName” value=“java:comp/env/jdbc/MyDataSourceName”/> </bean>
  • 13.
    Working with DataSources Creatinga connection pool <bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource”> <property name="url“ value=“jdbc:mysql://localhost/demo”/>> <property name="driverClassName“ value=“com.mysql.jdbc.Driver”/> <property name="username” value=“test”/> <property name=“password” value=“password”/> </bean>
  • 14.
  • 15.
    Overview of SpringJDBC features  As mentioned, provides framework so that Spring manages:  Resources  Transactions  Exceptions  Consistent exception hierarchy  Subclass RuntimeException  Specific and meaningful (no vendor error codes!)  Extensable
  • 16.
    Some Spring JDBCcallback interfaces  PreparedStatementCreator  Has one method – createPreparedStatement(Connection)  Responsible for creating a PreparedStatement  Does not need to handle SQLExceptions
  • 17.
    Some Spring JDBCcallback interfaces  SQLProvider  Has one method – getSql()  Typically implemented by PreparedStatementCreator implementers  Useful for debugging
  • 18.
    Some Spring JDBCcallback interfaces  RowCallbackHandler  Has one method – processRow(ResultSet)  Called for each row in ResultSet  Typically stateful
  • 19.
    Some Spring JDBCcallback interfaces  RowMapper  Has one method – mapRow(ResultSet rs, int rowNum)  Maps a single row to an Object
  • 20.
    Using JdbcTemplate  Central class for Spring JDBC framework  Uses callbacks “under the covers”  All you will need for most JDBC operations
  • 21.
    Using JdbcTemplate Code Example
  • 22.
    Spring Incrementers  Used to increment primary key value for newly persisted object  Implements DataFieldMaxValueIncrementer  Supports  Oracle sequences  DB2 sequences  PostgreSQL sequences  MySQL for non-auto-increment columns
  • 23.
    Using JdbcTemplate Code Example
  • 24.
    Hibernate intro  Open source ORM tool  Very mature (version 3.2 on horizon)  Feature-complete  Caching  Eager-fetching  Lazy-loading  Proxying
  • 25.
    Using Hibernate  Configure classes to be mapped through  Manually created configuration files  XDoclet generated configuration files  Annotations (JPA and Hibernate)  Configure global properties through hibernate.properties file  Hibernate class analogies  DataSource : SessionFactory  Connection : Session
  • 26.
    Using Spring withHibernate  Use Spring to configure Hibernate  Configure Hibernate mappings  Configure Hibernate properties  Wire dependant object to SessionFactory  Use HibernateTemplate as abstraction to Hibernate API  Manages obtaining Session from SessionFactory  Handles/converts exceptions  Manages transactions
  • 27.
    Using JdbcTemplate Code Example
  • 28.
    Spring Transaction Management  Supports programmatic (yuck!) and declarative (yeah!) transactions  Declarative transaction management achieved via Spring’s AOP  Declarative transactions can be defined in Spring configuration file or in annotations  Supports many transaction properties  Propagation  Isolation level  Rollback conditions
  • 29.
    Spring Proxy Overview depends on SomeClient DaoInterface is wired delegates ProxyBean DaoImpl
  • 30.
    Using JdbcTemplate Code Example
  • 31.
    Coming in Spring2.0  Support for AspectJ pointcut language  JPA support?  SimpleJdbcTemplate  Support generics  Support variable argument methods