Thursday, April 17, 2008

Integrating Spring and Hibernate: Transactions

In the previous post, I described different ways in which spring and hibernate can
be integrated. In this post I will describe how to use Spring's transaction features
in hibernate. The following methods of transaction management with spring and hibernate are discussed.
  1. Declarative Transaction Mangement with AOP Interceptors
  2. Schema-based Declarative Transaction Management
  3. Schema-based Declarative Transaction Management with Annotations
  4. Programmatic Transaction Management

The easiest way to check if transactions are working for this example is to remove the transaction declarations for the getStockQuote() method. Removing transactions will cause the following exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session

There's More ...
For this example, start off with the following as described in the "Integrating Spring and Hibernate" post.
  1. The bean StockQuoteBean
  2. The Portfolio classes : PortfolioDAO, PortfolioDAOSupport and PortfolioDAOTemplate
  3. The hibernate mapping file stockquote.hbm.xml

The following main class can be used:
package springhibernate;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringHibernateTest {


public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

IPortfolioService portfolioService = (IPortfolioService) ctx.getBean("portfolioService");
System.out.println("Portfolio Service type : " + portfolioService.getClass());
portfolioService.getStockQuote("123");
}


}
SpringHibernateTest.java

Note that here we use an Interface IPortfolioService, and also note the change to ApplicationContext instead of a BeanFactory.
The reason for using ApplicationContext is enable the use of AOP for declarative transaction management. Also we are not expecting any return to the main class as all the execution is expected to happen in the transaction context.

The Portfolio Service Interface:
package springhibernate;

import beans.StockQuoteBean;

public interface IPortfolioService {

public void getStockQuote(String id);

public void updateStockQuote(StockQuoteBean stockQuoteBean);

}
IPortfolioService.java

Declarative Transaction Management

Declarative transaction management in Spring has the advantage of being less invasive. There is no need for changing application code when using declarative transactions. All you have to do is to modify the application context.

The Service class will be same for all the modes of Declarative transaction management described below.
package springhibernate;

import beans.StockQuoteBean;
import dao.PortfolioDAO;


public class PortfolioService implements IPortfolioService {
private PortfolioDAO portfolioDAO;



public void getStockQuote(String id) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
System.out.println("Result in Service : " + result.getStockSymbol());

}

public void updateStockQuote(StockQuoteBean stockQuoteBean) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}

public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}

public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}

}
PortfolioService.java

Declarative Transaction Management with AOP Interceptor

In this method, you have to define a proxy for the bean that will be made transactional.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="myPortfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributeSource">
<value>springhibernate.PortfolioService.*=PROPAGATION_REQUIRED</value>
</property>
</bean>

<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="portfolioService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="myPortfolioService"></property>
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

</beans>
applicationContext.xml

Note that the transactionInterceptor and hibernateTransactionInterceptor are declared. While transactionInterceptor is used to set the transaction properties, the hibernateTransactionInterceptor will manage the hibernate transactions.

Schema-based Declarative Transaction Management

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="portfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* springhibernate.IPortfolioService.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config>

<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<tx:method name="*" propagation="REQUIRES_NEW" />
</tx:attributes>
</tx:advice>


<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

</beans>
applicationContext.xml
Using Schema-based declarative transaction management is a lot simpler and a lot cleaner. However it is adviced that this method not be used in conjunction with explicit auto-proxying using BeanNameAutoProxyCreator, as it might raise issues like advice not being woven etc. Note that the AOP pointcut is defined to be all methods on the IPortfolioService inteface.

Schema-based Declarative Transaction Management with Annotations

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="portfolioService" class="springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOTemplate"></property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven/>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

</beans>
applicationContext.xml
When using annotations, you only have to declare the transaction manager and add <tx:annotation-driven/> to the application context. If the transaction manager is named "transactionManager" then you don't have to declare a transaction-manager attribute for <tx:annotation-driven/> as it happens to be the default value for that attribute.
Also we have to declare the pointcuts in the Service class itself. Note that as annotations are not inherited, declaring the annotations has to be done at the class level.
@Transactional
public class PortfolioService implements IPortfolioService {
private PortfolioDAO portfolioDAO;...

Programmatic Transaction Management

For programmatic transaction management in spring, you will need a PlatformTransctionManger in your bean which will be used to create a TransactionTemplate. The TransactionTemplate is used in the same way the HibernateTemplate was used in previous example. Additionally you will have to create a HibernateTransactionManager as shown in the above example.
package springhibernate;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import beans.StockQuoteBean;
import dao.PortfolioDAO;

public class PortfolioServiceTransaction implements IPortfolioService{
private PortfolioDAO portfolioDAO;

private PlatformTransactionManager transactionManager;

public void getStockQuote(final String id) {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {

public void doInTransactionWithoutResult(TransactionStatus status) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
System.out.println("Symbol in transaction " + result.getStockSymbol());
}
});

}

public void updateStockQuote(final StockQuoteBean stockQuoteBean) {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {

public void doInTransactionWithoutResult(TransactionStatus status) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}
});

}

public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}

public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}

public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}

}
PortfolioService.java

Monday, April 14, 2008

Integrating Spring and Hibernate

This post applies to integrating Spring framework 2.5.3 and Hibernate 3.0.

The Spring framework provides extensive support for data access through the use of support classes (JdbcDaoSupport, JdbcTemplate etc.), and extensive exception hierarchy to wrap any platform specific SQLException into an exception in the spring exception hierarchy. Additionally Spring framework also provides good support for integrating with ORM technologies like Hibernate and iBatis etc. This post will show how to integrate Spring framework with Hibernate ORM. There's more ...
  1. Create the bean: The bean here represents a simple stock quote
    package beans;

    public class StockQuoteBean {
    private String quoteId;

    private String stockSymbol;

    private String name;

    public String getQuoteId() {
    return quoteId;
    }

    public void setQuoteId(String quoteId) {
    this.quoteId = quoteId;
    }

    public String getStockSymbol() {
    return stockSymbol;
    }

    public void setStockSymbol(String stockSymbol) {
    this.stockSymbol = stockSymbol;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }
    }
    StockQuoteBean.java
  2. Create a Hibernate Mapping file for the bean:
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <class name="beans.StockQuoteBean" table="STOCK_QUOTES" lazy="false">
    <id name="quoteId" column="quote_id">
    <generator class="assigned" />
    </id>

    <property name="stockSymbol">
    <column name="stock_symbol" />
    </property>
    <property name="name">
    <column name="name" />
    </property>
    </class>
    </hibernate-mapping>
    stockquote.hbm.xml

    The one important thing to note here is that in the declaration, a [lazy="false"] has been added to the mapping for the stockquote bean. The reason for this is that in hibernate 3, lazy initialization is turned on by default. This raises a problem when used with spring's HibernateCallback. The spring HibernateTemplate.execute() by default closes any open sessions upon completion. When used with lazy initialization you may get a LazyInitializationException like the following
    org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    If you want to use lazy initialization with HibernateCallback, you will have to use this within a transaction context. The javadoc for HibernateTemplate specifies this explicitly
    Note that operations that return an Iterator (i.e. iterate) are supposed
    to be used within Spring-driven or JTA-driven transactions (with
    HibernateTransactionManager, JtaTransactionManager, or EJB CMT). Else, the
    Iterator won't be able to read results from its ResultSet anymore, as the
    underlying Hibernate Session will already have been closed.

    Lazy loading will also just work with an open Hibernate Session, either within a
    transaction or within OpenSessionInViewFilter/Interceptor. Furthermore, some
    operations just make sense within transactions, for example: contains, evict,
    lock, flush, clear.
  3. The service class: The service class simply acts as an intermediary between the client and the DAO classes.
    package springhibernate;

    import beans.StockQuoteBean;
    import dao.PortfolioDAO;

    public class PortfolioService {
    private PortfolioDAO portfolioDAO;

    public StockQuoteBean getStockQuote(String id) {
    StockQuoteBean result = portfolioDAO.getStockQuote(id);
    return result;
    }

    public void updateStockQuote(StockQuoteBean stockQuoteBean) {
    portfolioDAO.updateStockQuote(stockQuoteBean);
    }

    public PortfolioDAO getPortfolioDAO() {
    return portfolioDAO;
    }

    public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
    this.portfolioDAO = portfolioDAO;
    System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
    }

    }
    PortfolioService.java
  4. The DAO interface:
    package dao;

    import beans.StockQuoteBean;

    public interface PortfolioDAO {
    public StockQuoteBean getStockQuote(String id);
    public void updateStockQuote(StockQuoteBean bean);
    public StockQuoteBean getStockQuote_hibernateTemplate(String id);
    public void updateStockQuote_hibernateTemplate(StockQuoteBean bean);
    }
    PortfolioDAO.java
  5. The DAO Classes: The DAO classes shows the different ways in which the Hibernate calls can be made using the Spring support classes. There are three primary ways in which these calls can be made
    1. Using the HibernateCallback
    2. Using the HibernateTemplate directly
    3. Using the hibernate native calls using Session
    Spring also provides two different ways to create the Data access objects that interact with Hibernate.
    1. Using Composition, with HibernateTemplate
    2. Using Inheritance by extending HibernateDaoSupport
    All these methods will be explained when used in the following sections.
    1. Using HibernateTemplate
      package dao;

      import java.sql.SQLException;
      import java.util.List;

      import org.hibernate.HibernateException;
      import org.hibernate.Session;
      import org.springframework.orm.hibernate3.HibernateCallback;
      import org.springframework.orm.hibernate3.HibernateTemplate;

      import beans.StockQuoteBean;

      public class PortfolioDAOTemplate implements PortfolioDAO{
      private HibernateTemplate hibernateTemplate;

      public PortfolioDAOTemplate() {
      System.out.println("Init transaction dao");
      }


      public StockQuoteBean getStockQuote(final String id) {

      HibernateCallback callback = new HibernateCallback() {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
      return session.load(StockQuoteBean.class, id);
      }
      };
      return (StockQuoteBean) hibernateTemplate.execute(callback);
      }

      public void updateStockQuote(final StockQuoteBean StockQuoteBean) {
      HibernateCallback callback = new HibernateCallback() {
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
      session.saveOrUpdate(StockQuoteBean);
      return null;
      }
      };
      hibernateTemplate.execute(callback);

      }

      public void updateStockQuote_hibernateTemplate(StockQuoteBean StockQuoteBean) {
      hibernateTemplate.update(StockQuoteBean);

      }
      public StockQuoteBean getStockQuote_hibernateTemplate(String id) {
      List<StockQuoteBean> transactions = hibernateTemplate.find("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?", id);
      return transactions.get(0);
      }


      public HibernateTemplate getHibernateTemplate() {
      return hibernateTemplate;
      }


      public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
      this.hibernateTemplate = hibernateTemplate;
      }



      }
      PortfolioDAOTemplate

      This class shows how to use the HibernateTemplate to make calls to Hibernate. The getStockQuote() and updateStockQuote() methods use HibernateCallback class, note that when using HibernateCallback, it is necessary to either do it in a transactional context or turn off lazy initialization. While the getStockQuote_hibernateTemplate() and updateStockQuote_hibernateTemplate() make calls using hibernateTemplate directly. Also note that the parameters to the getStockQuote(), and updateStockQuote() methods are marked final.
    2. Using HibernateDaoSupport
      package dao;

      import java.util.List;

      import org.hibernate.Query;
      import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

      import beans.StockQuoteBean;

      public class PortfolioDAOSupport extends HibernateDaoSupport implements PortfolioDAO {

      public void updateStockQuote(StockQuoteBean stockQuoteBean) {
      Query query = getSession().createQuery("update beans.StockQuoteBean set stockSymbol=? where quoteId=?");
      query.setString(0, stockQuoteBean.getStockSymbol());
      query.setString(1, stockQuoteBean.getQuoteId());
      query.executeUpdate();
      }
      public StockQuoteBean getStockQuote(String id) {
      Query query = getSession().createQuery("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?");
      query.setString(0, id);
      List results = query.list();
      if(results == null || results.size() == 0) {
      throw new RuntimeException("No result");
      }
      return (StockQuoteBean)results.get(0);
      }

      public void updateStockQuote_hibernateTemplate(StockQuoteBean StockQuoteBean) {
      getHibernateTemplate().update(StockQuoteBean);

      }
      public StockQuoteBean getStockQuote_hibernateTemplate(String id) {
      List<StockQuoteBean> transactions = getHibernateTemplate().find("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?", id);
      return transactions.get(0);
      }

      }
      PortfolioDAOSupport

      This class uses HibernateDaoSupport to get instances of HibernateTemplate, and the Hibernate Session. The getStockQuote() and updateStockQuote() in this class make calls to hibernate session directly.
  6. The application context
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <bean id="portfolioDAOTemplate" class="dao.PortfolioDAOTemplate">
    <property name="hibernateTemplate" ref="hibernateTemplate" />
    </bean>

    <bean id="portfolioDAOSupport" class="dao.PortfolioDAOSupport">
    <property name="hibernateTemplate" ref="hibernateTemplate" />
    </bean>

    <bean id="portfolioService" class="springhibernate.PortfolioService">
    <property name="portfolioDAO" ref="portfolioDAOSupport"></property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
    <property name="username" value="appUser" />
    <property name="password" value="password" />
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mappingResources">
    <list>
    <value>stockquote.hbm.xml</value>
    </list>
    </property>

    <property name="hibernateProperties">
    <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.generate_statistics">true</prop>
    </props>
    </property>
    </bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    </beans>
    applicationContext.xml
    • The SessionFactory is defined with the datasource and mapping-resources. The hibernate specific properties are defined under the hibernateProperties property.
    • The HibernateTemplate uses are reference to the SessionFactory.
    • The HibernateTemplate is used as a reference to the DAO classes.
    • The porfolioService bean in uses a reference to the PortfolioDAO, which can be switched between the dao.PortfolioDAOSupport and dao.PortfolioDAOTemplate beans
  7. The main class
    package springhibernate;


    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.core.io.Resource;

    import beans.StockQuoteBean;


    public class SpringHibernateTest {


    public static void main(String[] args) {
    Resource resource = new FileSystemResource("applicationContext.xml");
    BeanFactory factory = new XmlBeanFactory(resource);

    PortfolioService portfolioService = (PortfolioService) factory.getBean("portfolioService");

    StockQuoteBean result = portfolioService.getStockQuote("123");
    System.out.println(result.getStockSymbol());

    empResult.setStockSymbol("GOOG");
    portfolioService.updateStockQuote(result);
    }


    }
    SpringHibernateTest.java
  8. Necessary JAR files:
    • commons-logging-1.1.1.jar
    • hibernate3.jar
    • dom4j-1.6.1.jar
    • ojdbc14.jar
    • commons-collections-3.2.jar
    • log4j-1.2.15.jar
    • commons-dbcp.jar
    • commons-pool.jar
    • spring.jar
    • cglib-nodep-2.1_3.jar
    • antlr-2.7.6.jar
    • jta.jar

Friday, April 11, 2008

Struts 2 Custom Validators

Struts 2 allows the use of Custom validators through the @CustomValidator annotation. The @CustomValidator annotation takes two mandatory parameters, type and message
  • type: Refers to the "name" given to the validator in the validators.xml file.
  • message: Message to be displayed when this validator fails.
A custom validator can be implemented by extending the FieldValidatorSupport, or alternatively the ValidatorSupport classes. The following sample builds on the example built in the previous post, Struts 2 Validaton: Annotations.

To run this sample, follow these steps... There's More

  1. Create a simple struts project as described in the previous example, Struts 2 Validation : Annotations
  2. Create the new validator by extending the FieldValidatorSupport class
    package validators;

    import com.opensymphony.xwork2.validator.ValidationException;
    import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

    public class NumberFieldValidator extends FieldValidatorSupport {

    public void validate(Object object) throws ValidationException {
    String fieldName = getFieldName();
    Object value = this.getFieldValue(fieldName, object);

    if (!(value instanceof String)) {
    return;
    }

    String str = ((String) value).trim();
    if (str.length() == 0) {
    return;
    }

    try {
    Double.parseDouble(str);
    }catch(NumberFormatException nfe) {
    addFieldError(fieldName, object);
    return;
    }
    try {
    Integer.parseInt(str);
    }catch(NumberFormatException nfe) {
    addFieldError(fieldName, object);
    return;
    }

    }
    }
    NumberFieldValidator.java
    • The custom validator may extend the FieldValidatorSupport or the ValidatorSupport classes.
    • The FieldValidatorSupport class extends ValidatorSupport to add field specific information to the Field.
    • The is numeric check is performed by trying to convert the input string to Integer or Double and catching any exception.
    • The addFieldError method is used add any failed validations to the list of errors to be displayed.
    • The getFieldName and getFieldValue methods are implemented in the superclasses to retrieve the field name and field value for the field beign validated.
  3. Declare the new custom validator in the validators.xml file. The validators.xml file must be in the classpath of the application.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE validators PUBLIC
    "-//OpenSymphony Group//XWork Validator Config 1.0//EN"
    "http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
    <validators>
    <validator name="numericField" class="validators.NumberFieldValidator"/>
    </validators>
    validators.xml

    Note: The name attribute of the validator must match the type attribute of the @CustomValidator Annotation used in the Action class.
  4. Add the additional check to the Action class setPrice() method.
     @RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
    @CustomValidator(type = "numericField", message = "Price must be a number")
    public void setPrice(String price) {
    this.price = price;
    }
    AddTransactionAction.java

    Note: the type attribute of the @CustomValidator Annotation must match the name of the validator as defined in the validators.xml file.

Struts 2 Validation : Annotations

In a previous post, I described how to use validations in Struts 2, using XML validation rules. This post will show how to use Annotation based validation in Struts 2. For this example I used the add transaction part of google's portfolio manager (noticed that they do not have validations over there). Struts 2 provides a number of validators for XML based validation rules. All of them have respective annotations defined and can be used in place of XML validation rules. In the example, we will use the @RequiredStringValidator, @RegexFieldValidator and also see how to parameterize messages when using annotations.

Follow these steps to implement the example ... There's more

  1. Create a dynamic web project in Eclipse.
  2. Copy the following jar files into the WEB-INF/lib directory, all these files are available with sturts download.
    • struts2-core-2.0.11.1.jar
    • xwork-2.0.4.jar
    • freemarker-2.3.8.jar
    • commons-logging-1.1.1.jar
    • ognl-2.6.11.jar
  3. Update your web deployment desciptor to include the sturts filter dispatcher.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>struts2Validation</display-name>
    <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.FilterDispatcher
    </filter-class>
    </filter>
    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
    WEB-INF/web.xml
  4. Create the input JSP
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Add Transaction</title>
    </head>
    <body>
    <s:form action="addTransaction" validate="true" method="post">
    <s:fielderror />
    <table>
    <tr>
    <td>Symbol</td>
    <td><s:textfield name="symbol"></s:textfield></td>
    </tr>
    <tr>
    <td>Type</td>
    <td><s:select name="type" list="#{'':'Select One', 'BUY':'Buy','SELL':'Sell','BUY_COVER':'Buy to Cover','SELL_SHORT':'Sell Short'}">
    </s:select></td>
    </tr>
    <tr>
    <td>Date</td>
    <td><s:textfield name="date" ></s:textfield></td>
    </tr>
    <tr>
    <td>Number of Shares</td>
    <td><s:textfield name="numberOfShares"></s:textfield></td>
    </tr>
    <tr>
    <td>Price</td>
    <td><s:textfield name="price"></s:textfield></td>
    </tr>
    <tr>
    <td>Commission</td>
    <td><s:textfield name="comission"></s:textfield></td>
    </tr>
    <tr>
    <td>Notes</td>
    <td><s:textfield name="notes"></s:textfield></td>
    </tr>
    <tr>
    <td colspan="2"> <s:submit name="submit" value="submit"></s:submit>
    <s:submit name="submitNoValidate" value="submit without validation" method="noValidation"></s:submit> </td>

    </tr>
    </table>
    </s:form>
    </body>
    </html>
    transactions.jsp

    Note: The method="noValidation" indicates to struts that on submission, the noValidation() method will be invoked on the AddTransactionAction class.
  5. Create the output JSP
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Transaction Added</title>
    </head>
    <body>
    <s:bean name="actions.AddTransactionAction" id="addTransaction" ></s:bean>
    <table>
    <tr>
    <td colspan="2">The following transaction has been added to your portfolio</td>
    </tr>
    <tr>
    <td>Symbol</td>
    <td><s:label name="symbol" value="%{symbol}" /></td>
    </tr>
    <tr>
    <td>Type</td>
    <td><s:label name="type" value="%{type}" />
    </td>
    </tr>
    <tr>
    <td>Date</td>
    <td><s:label name="date" value="%{date}"/></td>
    </tr>
    <tr>
    <td>Number of Shares</td>
    <td><s:label name="numberOfShares" value="%{numberOfShares}"></s:label></td>
    </tr>
    <tr>
    <td>Price</td>
    <td><s:label name="price" value="%{price}"></s:label></td>
    </tr>
    <tr>
    <td>Commission</td>
    <td><s:label name="comission" value="%{comission}"></s:label></td>
    </tr>
    <tr>
    <td>Notes</td>
    <td><s:label name="notes" value="%{notes}"></s:label></td>
    </tr>
    </table>
    </body>
    </html>
    done.jsp
  6. Create the Action class
    package actions;

    import org.apache.struts2.interceptor.validation.SkipValidation;

    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
    import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
    import com.opensymphony.xwork2.validator.annotations.ValidatorType;
    import com.opensymphony.xwork2.validator.annotations.Validation;

    @Validation
    public class AddTransactionAction extends ActionSupport {

    private String symbol;
    private String type;
    private String date;
    private String numberOfShares;
    private String price;
    private String comission;
    private String notes;


    public String execute() throws Exception {
    System.out.println("In Execute");

    return SUCCESS;
    }

    @SkipValidation
    public String noValidation() throws Exception {
    System.out.println("In Novalidation");
    return SUCCESS;
    }


    public String getSymbol() {
    return symbol;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Symbol Required")
    public void setSymbol(String symbol) {
    this.symbol = symbol;
    }


    public String getType() {
    return type;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Type Required")
    public void setType(String type) {
    this.type = type;
    }


    public String getDate() {
    return date;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Date Required")
    @RegexFieldValidator(type=ValidatorType.FIELD, message="",key="date.error.message", expression = "[0-9][0-9]/[0-9][0-9]/[1-9][0-9][0-9][0-9]")
    public void setDate(String date) {
    this.date = date;
    }


    public String getNumberOfShares() {
    return numberOfShares;
    }


    @RequiredStringValidator(type = ValidatorType.FIELD, message = " Number of Shares Required")
    public void setNumberOfShares(String numberOfShares) {
    this.numberOfShares = numberOfShares;
    }


    public String getPrice() {
    return price;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
    public void setPrice(String price) {
    this.price = price;
    }


    public String getComission() {
    return comission;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Comission Required")
    public void setComission(String comission) {
    this.comission = comission;
    }


    public String getNotes() {
    return notes;
    }


    public void setNotes(String notes) {
    this.notes = notes;
    }
    }
    AddTransactionAction.java

    Note:
    • The annotation @Validation is used to indicate that the current action might need validation. The validations on a method level can be skipped using the @SkipValidation annotation on the method.
    • The method noValidations() uses the @SkipValidation annotation, you can see this when you click on "Submit without validation" in the JSP
    • The @RequiredStringValidator annotation is used to indicate a Required Strint similar to the following xml rule
      <validators>
      <field name="numberOfShares">
      <field-validator type="requiredstring">
      <message>Number of Share is required</message>
      </field-validator>
      </field>
      </validators>
    • On the date field, I used a @RegexFieldValidator annotation, so that the date field will be mandated to have a given format.
    • Parameterized messages: You will notice that the message attribute of the @RegexFieldValidator is set to an empty string, while the key is set to a value. This is due to the fact that the message attribute is mandatory, and the key attribute is used to denote the message key from the properties files. The parameters can be retrieved in the properties files using the ${date} notation where the "date" variable is expected to available in the value stack
  7. Create a definition for the action in struts.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

    <struts>
    <package name="struts2Validation" extends="struts-default">
    <action name="addTransaction"
    class="actions.AddTransactionAction">
    <result name="success">done.jsp</result>
    <result name="input">transactions.jsp</result>
    </action>
    </package>
    </struts>
    struts.xml

    Note: The result with name "input" is because the validator returns the result to input when validation fails.
  8. Create the properties file for messages
    date.error.message=Date ${date} is not properly formatted.
    package.properties

    Note: In the properties file, ${date} is used to retrieve the "date" value from the value stack, this is the way Struts 2 supports parameterization.

  9. Create the struts.properties file to set the theme to simple theme, so that you have more control how the UI components are laid out.
    struts.ui.theme=simple
    struts.properties

Tuesday, April 01, 2008

Integrating Struts 2.0 and tiles

I am currently evaluating some web frameworks for a pet project and was trying to implement Struts 2 with tiles. Neither the Sturts 2 website, nor the tiles website gave an easy way to integrated Struts 2 and tiles. It took me a while to get them to work together. This post describes a way I figured out how to integrate Struts 2 with tiles. Struts 2 provides a plugin for integrating tiles 2. This plugin is included in the complete bundle (struts-2.x.x.x-all.zip). The following are are the steps needed to integrate struts2 with tiles.
Skip to Sample Code
  1. Download the struts complete bundle from the struts 2 website
  2. Download tiles 2 from tiles 2 website
  3. Download the tiles dependencies from the jakarta commons site
    • Commons BeanUtils 1.7.0 or above
    • Commons Digester 1.8 or above
    • Commons Logging 1.1 or above
  4. Create the layout page, and related files (except the layout, all the other files are basic jsps )
    <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    <table width="100%" height="100%">
    <tr height="20%">
    <td colspan="2" align="center" bgcolor="skyblue">
    <tiles:insertAttribute name="header" /></td>
    </tr>
    <tr>
    <td bgcolor="cyan" width="75%"><tiles:insertAttribute name="body" /></td>
    </tr>
    <tr height="20%">
    <td colspan="2" align="center" bgcolor="skyblue"><tiles:insertAttribute name="footer" /></td>
    </tr>
    </table>
    </body>
    </html>
  5. Create the HelloWorld Action class
    package example;

    import com.opensymphony.xwork2.ActionSupport;

    public class HelloWorld extends ActionSupport {

    public String execute() throws Exception {
    System.out.println("Hello World");
    return SUCCESS;
    }
    }
  6. Configure the Web Deployment descriptor by adding a tiles listener to the web.xml file of your web application.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>tilesTest</display-name>
    <listener>
    <listener-class>
    org.apache.struts2.tiles.StrutsTilesListener
    </listener-class>
    </listener>
    <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.FilterDispatcher
    </filter-class>
    </filter>
    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
  7. Configure struts to work with tiles, this can be done by either
    1. Extending the sturts package from "tiles-default"
      <package name="tilesTest" extends="tiles-default">
    2. OR
    3. Declaring a new "result-type", tiles, that will map to "org.apache.struts2.views.tiles.TilesResult"
      <result-types>
      <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
      </result-types>
  8. Set the type of the results in the package to "tiles"
    <result name="success" type="tiles">helloworld.home</result>

    struts.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

    <struts>
    <package name="tilesTest" extends="struts-default">
    <result-types>
    <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
    </result-types>
    <action name="helloWorld" class="example.HelloWorld">
    <result name="success" type="tiles">helloworld.home</result>
    </action>
    </package>
    </struts>
    Note that the result "helloword.home" must match the definition name in tiles.xml file.

  9. Create definitions for tiles in WEB-INF/tiles.xml file.
    <!DOCTYPE tiles-definitions PUBLIC
    "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
    "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
    <tiles-definitions>
    <definition name="helloworld.home" template="/layouts/layout.jsp">
    <put-attribute name="header" value="/layouts/header.jsp" />
    <put-attribute name="body" value="/index.html" />
    <put-attribute name="footer" value="/layouts/footer.jsp" />
    </definition>
    </tiles-definitions>
  10. The following is a list of jar files used for this example (copied to the WEB-INF/lib directory)
    • commons-beanutils.jar
    • commons-digester-1.8.jar
    • commons-logging-1.1.1.jar
    • freemarker-2.3.8.jar
    • ognl-2.6.11.jar
    • struts2-core-2.0.11.1.jar
    • struts2-tiles-plugin-2.0.11.1.jar
    • tiles-api-2.0.5.jar
    • tiles-core-2.0.5.jar
    • tiles-jsp-2.0.5.jar
    • xwork-2.0.4.jar
  11. This example was implemented on tomcat 6.0.16, with Java 5 update 11

Popular Posts