Role and Competency management - iCALMS - PowerPoint by linzhengnd


									Part III. Portable Service Abstractions

Buenos Aires, June 2009.
 Introduction
 Transaction management
 DAO support
 Data access with JDBC
 Data access with ORM
 Testing with Spring
 Summary
 Transaction management
 DAO support
 Data access with JDBC
 Data access with ORM
 Summary
At it’s core, Spring provides:

•   Dependency Injection container
     – Effectively organize your dependencies, takes care of plumbing.
     – Facilitate good programming practices, as programming to interfaces.
     – Build flexible applications very easy to test and configure.

•   AOP support for handling crosscutting concerns
     – Provides J2EE services to POJOs.
     – E.g.: transaction management, security, logging, auditing, etc.
     – Portable between applications servers (no vendor lock in).

•   Portable Service Abstractions
     – Simplified APIs for many 3rd party frameworks (Hibernate, JDBC, Quartz, JMX, ...).

These together enable you to write powerful, scalable applications using POJOs.
•   Many Java EE APIs are very low-level
     – Need to write lots of repetitive code
     – Often error-prone
     – Exception handling can be painful - e.g. checked exceptions

•   Spring provides higher level APIs
     – Encapsulate low-level APIs
     – Eliminate boilerplate code
     – Simplified exception handling

     ⇒ Simpler application code
Spring provides abstraction for:

•   Transaction Management
•   JDBC
•   ORM frameworks:
     – Hibernate
     – JPA
     – Toplink
     – iBATIS
•   JavaMail
•   JMX
•   RMI
•   JMS
•   Quartz
•   …

          Allows access to these frameworks without knowing how they actually work.
 Introduction

  Transaction management
 DAO support
 Data access with JDBC
 Data access with ORM
 Summary
•   Interception around advive is the most fundamental advice type in Spring. AOP Alliance

•   The advice itself is represented by a bean, and must implement one of the advice
    interfaces (Spring 1.2 AOP support).

public class GreetingsInterceptor implements MethodInterceptor {
     public Object invoke(MethodInvocation invocation) throws Throwable {
          System.out.println("**** HI from INTERCEPTOR !!! ****");
          Object rval = invocation.proceed();
          System.out.println("**** GOODBYE from INTERCEPTOR !!! ****");
          return rval;
•   An advisor is like a small self-contained aspect that has a single piece of advice. It’s
    defined with the <aop:advisor> tag.

•   This is the new xml for the interceptor aspect:
     <bean id="counter" class="service.CounterImpl" />
     <bean id="greetingsInterceptor" class="aspect.GreetingsInterceptor" />
          <aop:pointcut id="myPointcut" expression="execution(* *.go*(..))"/>
          <aop:advisor advice-ref="greetingsInterceptor" pointcut-ref="myPointcut"/>
•   Console output:
**** HI from INTERCEPTOR !!! ****
counter = 0
counter = 1
counter = 2
counter = 3
counter = 4
counter = 5
counter = 6
counter = 7
counter = 8
counter = 9
counter = 10
**** GOODBYE from INTERCEPTOR !!! ****
•     Spring does not directly manage transactions.
•     Use transaction managers that delegate responsibility for transaction management to
      a platform-specific transaction implementation provided by either JTA or the persistence
•     Each transaction manager acts as a façade to a platform-specific transaction
•     Makes it possible for you to work with a transaction in Spring with little regard to what
      the actual transaction implementation is.
•     To use a transaction manager, you’ll need to declare it in your application context. For

    <bean id="transactionManager"
         <property name="dataSource" ref="dataSource"/>
•   Manages JDBC connections
     – Opens and closes JDBC connections
     – Stores connection in a ThreadLocal

•   Manages transactions
     – Connection.setAutoCommit(false)
     – Connection.commit()
     – Connection.rollback()
Declare the Transaction Manager bean:
<bean id="transactionManager"
     <property name="dataSource" ref="dataSource"/>

Declare the Transaction Advice bean.
<tx:advice id="tx-advice">
          <tx:method name="get*" read-only="true"/>
          <tx:method name="*" propagation="REQUIRED"/>

Declare the Transaction Interceptor:
     <aop:pointcut id=“service” expression="execution(* service.*.*(..))"/>
     <aop:advisor pointcut-ref=“service“ advice-ref="tx-advice"/>
 Introduction
 Transaction management

  Data access with Spring
 Summary
•    Service objects delegate data access to DAOs interfaces.

•   This makes the service objects easily testable. You could create mock
    implementations for the DAOs.

•   The data access layer is accessed in a persistence technology-agnostic manner.
    The Problem
•   JDBC force you to catch SQLExceptions. Most of them indicate a fatal condition, little
    can be done at runtime. Why catch them?
•   SQLException is the exception thrown for all data problems: is to generic.
•   Persistence frameworks like Hibernate offer many different exceptions. But they are
    propietary to Hibernate. You will spread them in your code.

    Spring solution
•   Provides several data access exceptions, each descriptive of the problem that they’re
•   They are not associated with any particular persistence solution. Consistent regardless
    of which persistence provider you use.
•   They are all unchecked exceptions. No more (empty…) catch blocks. This leaves the
    decision of wheter to catch an exception to the developer.
•    Spring separates the fixed and variable parts of the data access process into
    templates and callbacks.

•   Spring comes with several data access templates, depending the persistence
    mechanism (e.g. JdbcTemplate, HibernateTemplate, etc)
    <bean id="jdbcTemplate“ class="org.springframework.jdbc.core.JdbcTemplate">
         <property name="dataSource" ref="dataSource" />
•   DAO Support Classes are meant to be subclassed by your own DAO classes.

•   You can call the getTemplate method to hava direct access to the underlying data
    access template. E.g. getJdbcTemplate(), get HibernateTemplate().

•   You have also access to the class the persistence platform uses to communicate
    with the database. E.g. getConnection() for the JdbcDaoSupport, getSessionFactory()
    for HibernateDaoSupport.
•   First, declare the dataSource
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
     <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
     <property name="url" value="jdbc:hsqldb:hsql://localhost/testDB"/>
     <property name="username" value="sa"/>
     <property name="password" value=""/>
•      JDBC code for addBook (26 lines)                   •     Using JdbcDaoSupport (3 lines)

    private static final String ADD_BOOK =                    private static final String ADD_BOOK =
          "insert into books (id, name, author) values              "insert into books (id, name, author) values
          (?, ?, ?)";                                               (?, ?, ?)";
    public void addBook(Book book) {                          public void addBook(Book book) {
          Connection conn = null;                                   getSimpleJdbcTemplate().update(ADD_BOOK,
          PreparedStatement stmt = null;                            book.getId(), book.getName(),
          try {                                                     book.getAuthor());
                conn = dataSource.getConnection();            }
                stmt = conn.prepareStatement(ADD_BOOK);
                stmt.setInt(1, book.getId());
                stmt.setString(2, book.getName());
                stmt.setString(3, book.getAuthor());
          } catch (SQLException e) {
          } finally {
                try {
                      if (stmt != null) {
                      if (conn != null) {
                } catch (SQLException e) {
•     Define a DataSource bean
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
         <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
         <property name="username" value=“pepe"/>
         <property name="password" value=“1234"/>

•     Define a Session Factory bean
<bean id="sessionFactory"
     <property name="annotatedClasses">
     <property name="dataSource“ ref="dataSource" />
     <property name="hibernateProperties">
               <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
•     Define an Hibernate Template bean
    <bean id="hibernateTemplate“ class="org.springframework.orm.hibernate3.HibernateTemplate">
         <property name="sessionFactory" ref="sessionFactory" />

•     Define a Transaction Manager bean
<bean id="transactionManager“
     <property name="sessionFactory">
          <ref bean="sessionFactory" />

•     Define a Parent DAO bean for CRUD operations
    <bean id="baseDao" abstract="true" class="demo.dao.HibernateGenericDAO">
         <property name="hibernateTemplate" ref="hibernateTemplate" />
•   Define an Transaction Proxy Template bean
<bean id="parentService"
     <property name="transactionManager" ref="transactionManager" />
     <property name="transactionAttributes">
               <prop key="*">PROPAGATION_REQUIRED</prop>

•   Service interface and implementation
<bean id="contactServiceImpl" class="demo.service.impl.ContactServiceImpl">
     <property name="contactDAO" ref="contactDAOImpl"/>

<bean id="contactService" parent="parentService">
     <property name="target" ref="contactServiceImpl"/>
     <property name="proxyInterfaces" value="demo.service.ContactService" />
•   DAO interface and implementation
<bean id="contactDAOImpl" class="demo.dao.impl.HibernateContactDAO" parent="baseDao" />

<bean id="contactDAO" parent="parentService">
     <property name="target" ref="contactDAOImpl" />
 Introduction
 Transaction management
 DAO support
 Data access with JDBC
 Data access with ORM

                          Improved SOC
Spring framework:         DRY code
 Dependency injection    Simpler code
 AOP                     Improved maintainability
 Service abstractions    Easier to develop and test

                          Let’s you focus on the core problem
Thank You

To top