Showing posts with label persistence. Show all posts
Showing posts with label persistence. Show all posts

Monday, July 10, 2017

Mybatis Spring Integration

This post will give a quick introduction into integrating MyBatis and Spring with a very basic application. I will describe only the integration using XML based configuration. As always with MyBatis, this starts with setting up SqlSessionFactory from Spring. Instead of configuring the datasource and mapping in mybatis-config.xml, all configuration will be setup in Spring configuration. The only additional configuration will be the Mapper.xml file.

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

Tuesday, April 10, 2007

Native Queries with Hibernate Annotations

Hibernate EntityManager implements the programming interfaces and lifecycle rules as defined by the EJB3 persistence specification. Together with Hibernate Annotations, this wrapper implements a complete (and standalone) EJB3 persistence solution on top of the mature Hibernate core. In this post I will describe how map native queries (plain SQL) using Hibernate Annotations. Hibernate Annotations supports the use of Native queries through the @NamedNativeQuery and the @SqlResultSetMapping annotations.
  • @NamedNativeQuery: Specifies a native SQL named query.
  • @SqlResultSetMapping: Used to specify the mapping of the result of a native SQL query.
You will not need any EJB container support. At a minimum, you will need Hibernate core and Hibernate Annotations. The entire list of required Jar files is provided at the end.
  1. The Hibernate Configuration File: Nothing new here. Except that there are no mappings defined. I used programmatic declaration of mapping for this example as shown in the following steps.
    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

    <hibernate-configuration>
    <session-factory>
    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property>
    <property name="connection.username">scott</property>
    <property name="connection.password">tiger</property>
    <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
    <property name="hibernate.current_session_context_class">thread</property>
    </session-factory>
    </hibernate-configuration>
    hibernate.cfg.xml
  2. The Entity class:
    package data;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EntityResult;
    import javax.persistence.FieldResult;
    import javax.persistence.Id;
    import javax.persistence.NamedNativeQuery;
    import javax.persistence.SqlResultSetMapping;

    @Entity
    @SqlResultSetMapping(name = "implicit", entities = @EntityResult(entityClass = data.Employee.class))
    @NamedNativeQuery(name = "implicitSample", query = "select e.empno empNumber, e.ename empName, e.job empJob, e.sal empSalary, salg.grade empGrade from emp e, salgrade salg where e.sal between salg.losal and salg.HISAL", resultSetMapping = "implicit")
    //@SqlResultSetMapping(name = "explicit", entities = { @EntityResult(entityClass = data.Employee.class, fields = {
    // @FieldResult(name = "empNumber", column = "empno"),
    // @FieldResult(name = "empName", column = "ename"),
    // @FieldResult(name = "empJob", column = "job"),
    // @FieldResult(name = "empSalary", column = "sal"),
    // @FieldResult(name = "empGrade", column = "grade") }) })
    //@NamedNativeQuery(name = "implicitSample",
    // query = "select e.empno empno, e.ename ename, e.job job, e.sal sal, salg.grade grade from emp e, salgrade salg where e.sal between salg.losal and salg.HISAL", resultSetMapping = "explicit")
    public class Employee {

    private String empNumber;

    private String empName;

    private String empJob;

    private Double empSalary;

    private int empGrade;

    @Column
    @Id
    public int getEmpGrade() {
    return empGrade;
    }

    public void setEmpGrade(int empGrade) {
    this.empGrade = empGrade;
    }

    @Column
    public String getEmpJob() {
    return empJob;
    }

    public void setEmpJob(String empJob) {
    this.empJob = empJob;
    }

    @Column
    public String getEmpName() {
    return empName;
    }

    public void setEmpName(String empName) {
    this.empName = empName;
    }

    @Column
    public String getEmpNumber() {
    return empNumber;
    }

    public void setEmpNumber(String empNumber) {
    this.empNumber = empNumber;
    }

    @Column
    public Double getEmpSalary() {
    return empSalary;
    }

    public void setEmpSalary(Double empSalary) {
    this.empSalary = empSalary;
    }

    }
    Employee.java
    • The implitic mapping (the uncommented @NamedNativeQuery and @SqlResultSetMapping declarations are used for implicitly mapping the ResultSet to the entity class. Note that the SQL column names match the field names in the class. If the names do not match then you can set the name attribute of the @Column annotation to the column name in the query.
    • The commented @NamedNativeQuery and the @SqlResultSetMapping declarations explicitly map the fields to the columns. This will come in handy when using joins and composite keys etc.
    • Note the package definitions refer to javax.persistence and not the hibernate packages. If the packages are not declared properly, you will most likely end up with some exceptions like the following
      org.hibernate.hql.ast.QuerySyntaxException: Employee is not mapped.
      While there are other causes for this exception, the package declarations did cause a little trouble for me.
  3. The Client:
    import java.util.List;

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.cfg.Configuration;

    import data.Employee;

    public class Client {

    public static void main(String[] args) {
    Configuration config = new AnnotationConfiguration().addAnnotatedClass(Employee.class).configure();

    SessionFactory sessionFactory = config.buildSessionFactory();
    Session session = sessionFactory.getCurrentSession();

    List result = null;
    try {
    session.beginTransaction();

    result = session.getNamedQuery("implicitSample").list();
    System.out.println("Result size : " + result.size());
    session.getTransaction().commit();
    } catch (Exception e) {
    e.printStackTrace();
    }
    System.out.println(result.size());
    }

    }
    Client.java
  4. Jar Files: The following jar files need to be included in the classpath
    hibernate3.jar
    commons-collections-2.1.1.jar
    antlr-2.7.6.jar
    commons-logging-1.0.4.jar
    hibernate-annotations.jar
    ejb3-persistence.jar
    hibernate-commons-annotations.jar
    dom4j-1.6.1.jar
    ojdbc14.jar
    jta.jar
    log4j-1.2.11.jar
    xerces-2.6.2.jar
    xml-apis.jar
    cglib-2.1.3.jar
    asm.jar
    All the Jar files will be available in the hibernate download. The hibernate-annotations.jar file is available in the hibernate annotations download.
This example was tested on Java 5 Update 9 with Hibernate version 3.2.3 and Hibernate Annotations Version: 3.3.0.GA.

Monday, January 29, 2007

Integrating Struts 2.0 with Spring

In the past, I posted an example on how to use Displaytag with Struts and Spring, using Spring JDBC for data access(1, 2). In this post, I will describe how to do the same using Struts 2.0. The only major step that needs to be done here is to override the default Struts 2.0 OjbectFactory. Changing the ObjectFactory to Spring give control to Spring framework to instantiate action instances etc. Most of the code is from the previous post, but I will list only the additional changes here.
  1. Changing the default Object factory: In order to change the Ojbect factory to Spring, you have to add a declaration in the struts.properties file.
    struts.objectFactory = spring
    struts.devMode = true
    struts.enable.DynamicMethodInvocation = false
    src/struts.properties
  2. The Action class: Here is the code for the action class
    package actions;

    import java.util.List;

    import business.BusinessInterface;

    import com.opensymphony.xwork2.ActionSupport;

    public class SearchAction extends ActionSupport {
    private BusinessInterface businessInterface;

    private String minSalary;

    private String submit;

    private List data;

    public String getSubmit() {
    return submit;
    }

    public void setSubmit(String submit) {
    this.submit = submit;
    }

    public BusinessInterface getBusinessInterface() {
    return businessInterface;
    }

    public String execute() throws Exception {
    try {
    long minSal = Long.parseLong(getMinSalary());
    System.out.println("Business Interface: " + businessInterface + "Minimum salary : " + minSal);
    data = businessInterface.getData(minSal);
    System.out.println("Data : " + data);

    } catch (Exception e) {
    e.printStackTrace();
    }

    return SUCCESS;
    }

    public void setBusinessInterface(BusinessInterface bi) {
    businessInterface = bi;
    }

    public String getMinSalary() {
    return minSalary;
    }

    public void setMinSalary(String minSalary) {
    this.minSalary = minSalary;
    }

    public List getData() {
    return data;
    }

    public void setData(List data) {
    this.data = data;
    }
    }
    SearchAction.java
    • The Action class here does not have access to the HttpServetRequest and HttpServletResponse. Hence the action class itself was changed to the session scope for this example (see below)
    • In order for the action class to be aware of the Http Session, the action class has to implement the ServletRequestAware interface, and define a setServletRequest method, which will be used to inject the ServletRequest into the action class.
    • The BusinessInterface property is injected by Spring framework.
  3. The struts Configuration:
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
    <package name="Struts2Spring" namespace="/actions" extends="struts-default">
    <action name="search" class="actions.SearchAction">
    <result>/search.jsp</result>
    </action>
    </package>
    </struts>
    src/struts.xml
    • The action's class attribute has to map the id attribute of the bean defined in the spring bean factory definition.
  4. The Spring bean factory definition
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
    default-autowire="autodetect">
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName">
    <value>oracle.jdbc.driver.OracleDriver</value>
    </property>
    <property name="url">
    <value>jdbc:oracle:thin:@localhost:1521:orcl</value>
    </property>
    <property name="username">
    <value>scott</value>
    </property>
    <property name="password">
    <value>tiger</value>
    </property>
    </bean>

    <!-- Configure DAO -->
    <bean id="empDao" class="data.DAO">
    <property name="dataSource">
    <ref bean="dataSource"></ref>
    </property>
    </bean>
    <!-- Configure Business Service -->
    <bean id="businessInterface" class="business.BusinessInterface">
    <property name="dao">
    <ref bean="empDao"></ref>
    </property>
    </bean>
    <bean id="actions.SearchAction" name="search" class="actions.SearchAction" scope="session">
    <property name="businessInterface" ref="businessInterface" />
    </bean>
    </beans>
    WEB-INF/applicationContext.xml
    • The bean definition for the action class contains the id attribute which matches the class attribute of the action in struts.xml
    • Spring 2's bean scope feature can be used to scope an Action instance to the session, application, or a custom scope, providing advanced customization above the default per-request scoping.

  5. The web deployment descriptor
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts2Spring</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>

    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
    web.xml
    The only significant addition here is that of the RequestContextListener. This listener allows Spring framework, access to the HTTP session information.
  6. The JSP file: The JSP file is shown below. The only change here is that the action class, instead of the Data list is accessed from the session.
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://displaytag.sf.net" prefix="display"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <%@ page import="actions.SearchAction,beans.Employee,business.Sorter,java.util.List,org.displaytag.tags.TableTagParameters,org.displaytag.util.ParamEncoder"%>
    <html>
    <head>
    <title>Search page</title>
    <link rel="stylesheet" type="text/css" href="/StrutsPaging/css/screen.css" />
    </head>
    <body bgcolor="white">
    <s:form action="/actions/search.action">
    <table>
    <tr>
    <td>Minimum Salary:</td>
    <td><s:textfield label="minSalary" name="minSalary" /></td>
    </tr>
    <tr>
    <td colspan="2"><s:submit name="submit" /></td>
    </tr>
    </table>
    </s:form>
    <jsp:scriptlet>

    SearchAction action = (SearchAction)session.getAttribute("actions.SearchAction");
    session.setAttribute("empList", action.getData());
    if (session.getAttribute("empList") != null) {
    String sortBy = request.getParameter((new ParamEncoder("empTable")).encodeParameterName(TableTagParameters.PARAMETER_SORT));
    Sorter.sort((List) session.getAttribute("empList"), sortBy);

    </jsp:scriptlet>

    <display:table name="sessionScope.empList" pagesize="4" id="empTable" sort="external" defaultsort="1" defaultorder="ascending" requestURI="">
    <display:column property="empId" title="ID" sortable="true" sortName="empId" headerClass="sortable" />
    <display:column property="empName" title="Name" sortName="empName" sortable="true" headerClass="sortable" />
    <display:column property="empJob" title="Job" sortable="true" sortName="empJob" headerClass="sortable" />
    <display:column property="empSal" title="Salary" sortable="true" headerClass="sortable" sortName="empSal" />
    </display:table>
    <jsp:scriptlet>
    }
    </jsp:scriptlet>

    </body>
    </html:html>
    search.jsp
  7. The Other required classes: The following other classes have been used for the example, and they can be obtained from the previous posts (1, 2).
    • Employee.java
    • BusinessInterface.java
    • Sorter.java
    • DAO.java
    • EmpMapper.java

Tuesday, January 16, 2007

Handling Oracle Large Objects with JDBC

LOBs (Large OBjects) are are designed to support large unstructured data such as text, images, video etc. Oracle supports the following two types of LOBs:
  • Character Large Object (CLOB) and Binary Large Object(BLOB) are stored in the database either in-line in the table or in a separate segment or tablespace.
  • BFILEs are large binary data objects stored in operating system files outside of database tablespaces.
Oracle extension classes are provided to support these types objects in JDBC like oracle.sql.CLOB, oracle.sql.BLOB. While you can use java.sql.Blob and java.sql.Clob, oracle extensions provide added functionalities, such as adding bytes specific positions (getBytes(int pos, byte[] data) etc.

Working with LOB Data

CLOB and the BLOB objects are not created and managed in the same way as the ordinary types such as VARCHAR. To work with LOB data, you must first obtain a LOB locator. Then you can read or write LOB data and perform data manipulation. Use the ResultSet's getBlob method to obtain the LOB locator, and then you can obtain the a Stream of the blob to read/write to the Blob
Blob blob = rs.getBlob(1);
InputStream is = blob.getBinaryStream();
OutputStream os = blob.setBinaryStream(1);
The following example shows how to insert, read and write Blobs to Oracle from Java. The table here has only two columns (IMAGE_ID and IMAGE) IMAGE is a BLOB.
package data;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BlobTest {

public void insertBlob(String imageId, String fileName) {
Connection conn = null;
try {
conn = getConnection();
if (!fileName.equals("")) {
PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGES VALUES(?, ?)");
ps.setString(1, imageId);
FileInputStream fis = new FileInputStream(fileName);
ps.setBinaryStream(2, fis, fis.available());
ps.execute();
ps.close();
} else {
PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGES VALUES (?, empty_blob())");
ps.setString(1, imageId);
ps.execute();
ps.close();

}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public void readBlob(String fileName) {
Connection conn = null;
try {
conn = getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT IMAGE FROM IMAGES");
while (rs.next()) {
// The following two lines can be replaced by
// InputStream is = rs.getBinaryStream(1);
Blob blob = rs.getBlob(1);
InputStream is = blob.getBinaryStream();
FileOutputStream fos = null;

fos = new FileOutputStream("c:/TEMP/" + fileName);
byte[] data = new byte[1024];
int i = 0;
while ((i = is.read(data)) != -1) {
fos.write(data, 0, i);
}
}
conn.close();

} catch (Exception e) {
e.printStackTrace();
}
}

public void writeBlob(String fileName) {
Connection conn = null;
try {
conn = getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT IMAGE FROM IMAGES FOR UPDATE");
while (rs.next()) {
Blob blob = rs.getBlob(1);
System.out.println(blob);
OutputStream os = blob.setBinaryStream(1);
FileInputStream fis = null;
fis = new FileInputStream("c:/TEMP/" + fileName);
byte[] data = new byte[1];
int i;
while ((i = fis.read(data)) != -1) {
os.write(data, 0, i);
}
os.close();
break;
}
conn.close();

} catch (Exception e) {
e.printStackTrace();
}
}

private Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "scott", "tiger");
return conn;
}

public static void main(String[] args) {
BlobTest blobTest = new BlobTest();
blobTest.insertBlob("img1", "");
blobTest.writeBlob("2.gif");

}
}
BlobTest.java

Insert Blob into Oracle

The insertBlob method takes the image id and the image file name as arguments. If the image file is an empty string, then an empty blob is inserted into the table. The empty_blob() function returns an empty locator of type BLOB, this is used in the INSERT.

Read from a Blob

The getBinaryStream of java.sql.Blob class returns an InputStream, which can be used to read from the blob.

Write to a Blob

The writeBlob method writes to the first row retrieved from the table. The SQL statement uses FOR UPDATE. In the absence of FOR UPDATE, you will get an IOException
java.io.IOException: ORA-22920: row containing the LOB value is not locked
at oracle.jdbc.driver.DatabaseError.SQLToIOException(DatabaseError.java:517)
at oracle.jdbc.driver.OracleBlobOutputStream.flushBuffer(OracleBlobOutputStream.java:214)
at oracle.jdbc.driver.OracleBlobOutputStream.close(OracleBlobOutputStream.java:179)
at data.BlobTest.writeBlob(BlobTest.java:90)
at data.BlobTest.main(BlobTest.java:111)
The following article describes how to handle CLOB using JDBC

Wednesday, December 27, 2006

Data Access with Spring and JPA

The JDBC abstraction layer of Spring framework offers an understandable exception hierarchy, simplifies error handling, and greatly reduces the amount of code you'll need to write. Spring 2.0 has support for using JPA in the Data Access Layer. In this post, I will describe a step-by-step approach to implementing a Web Application that uses Spring 2.0 and Java Persistence API for Data Access. The example is the same one that I used in the previous persistence examples. This example is implemented using Spring 2.0 on Glassfish.
  1. The Entity Class: The Entity class is the Employee class shown below:
    package beans;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name = "EMP")
    public class Employee {

    private long empId;

    private String empName;

    private String empJob;

    private long empSal;

    @Id
    @Column(name = "EMPNO")
    public long getEmpId() {
    return empId;
    }

    public void setEmpId(long empId) {
    this.empId = empId;
    }

    @Column(name = "JOB")
    public String getEmpJob() {
    return empJob;
    }

    public void setEmpJob(String empJob) {
    this.empJob = empJob;
    }

    @Column(name = "ENAME")
    public String getEmpName() {
    return empName;
    }

    public void setEmpName(String empName) {
    this.empName = empName;
    }

    @Column(name = "EMPSAL")
    public long getEmpSal() {
    return empSal;
    }

    public void setEmpSal(long empSal) {
    this.empSal = empSal;
    }
    }
    Employee.java
  2. The JSP page: The JSP page is also the same as used previously and is shown below.
    <jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:c="urn:jsptld:http://java.sun.com/jsp/jstl/core">
    <jsp:directive.page contentType="text/html; charset=UTF-8" />
    <jsp:directive.page
    import="org.springframework.web.context.support.XmlWebApplicationContext,org.springframework.beans.BeanUtils,org.springframework.web.context.ConfigurableWebApplicationContext, org.springframework.beans.factory.BeanFactory, data.DAO" />
    <link rel="stylesheet" type="text/css" href="css/screen.css" />
    <jsp:scriptlet>
    int pageNumber=1;
    if(request.getParameter("page") != null) {
    session.setAttribute("page", request.getParameter("page"));
    pageNumber = Integer.parseInt(request.getParameter("page"));
    } else {
    session.setAttribute("page", "1");
    }
    String nextPage = (pageNumber +1) + "";
    ConfigurableWebApplicationContext wac =
    (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(XmlWebApplicationContext.class);
    wac.setServletContext(this.getServletContext());
    wac.refresh();
    session.setAttribute( "EmpList", ((DAO)wac.getBean("dao")).getData(pageNumber));
    System.out.println(((java.util.List)session.getAttribute("EmpList")).size());
    String myUrl = "pagingEmp.jsp?page=" + nextPage;
    System.out.println(myUrl);

    pageContext.setAttribute("myUrl", myUrl);
    </jsp:scriptlet>
    <h2 align="center">Emp Table with Display tag</h2>
    <jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean>
    <table>
    <tr>
    <th>Employee Id</th>
    <th>Name</th>
    <th>Job</th>
    <th>Salary</th>
    </tr>
    <c:forEach items="${EmpList}" var="emp" begin="0" end="10">
    <tr>
    <td><c:out value="${emp.empId}"></c:out></td>
    <td><c:out value="${emp.empName}"></c:out></td>
    <td><c:out value="${emp.empJob}"></c:out></td>
    <td><c:out value="${emp.empSal}"></c:out></td>
    </tr>
    </c:forEach>

    <tr>
    <td colspan="2"></td>
    <td colspan="2"><a href="${pageScope.myUrl}">nextPage</a></td>
    </tr>
    </table>
    </jsp:root>
    pagingEmp.jsp
  3. The Application Context: The application context is shown below:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <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/orcl" />
    <property name="username" value="scott" />
    <property name="password" value="tiger" />
    </bean>
    <bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="myPersistenceUnit" />

    <property name="dataSource" ref="dataSource" />
    <property name="loadTimeWeaver">
    <bean class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
    </property>
    <property name="jpaDialect">
    <bean class="org.springframework.orm.jpa.vendor.TopLinkJpaDialect" />
    </property>
    <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
    <property name="showSql" value="true" />
    <property name="generateDdl" value="false" />
    <property name="databasePlatform" value="oracle.toplink.essentials.platform.database.oracle.OraclePlatform" />
    </bean>
    </property>
    </bean>

    <bean id="dao" class="data.DAO">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    </beans>
    WEB-INF/applicationContext.xml
  4. The Data Access Object: The data access object extends the JpaDaoSupport. JpaDaoSupport like JdbcTemplate implements most of the boiler-plate code for implementing JPA data access.
    package data;

    import java.util.List;

    import org.springframework.orm.jpa.JpaTemplate;
    import org.springframework.orm.jpa.support.JpaDaoSupport;

    public class DAO extends JpaDaoSupport {
    public long empId;
    public String empName;
    public String empJob;
    public long empSal;

    public List getData(long minSal) {
    JpaTemplate daoTmplt = getJpaTemplate();
    System.out.println("Creating query.");
    List result = null;
    try {
    result = daoTmplt.find("select e from Employee e");
    }catch(Throwable e) {
    e.printStackTrace();
    }
    return result;
    }
    }
    DAO.java
  5. The persistence xml: The persistence XML file does not have any persistence description as used in the JPA post. This is because it is defined in the application context XML file.
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL"></persistence-unit>
    </persistence>
    src/META-INF/persistence.xml
  6. The Web Deployment Descritor: The web deployment descriptor is shown below. Note the listener definition for org.springframework.web.context.ContextLoaderListener.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>SpringJpa</display-name>
    <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>
    <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    </web-app>
    web.xml
  7. Setup: In order to run the example on Glassfish, you have to create an EAR and install the EAR instead of trying to deploy a WAR file on Glassfish. Deploying WAR files gives some classloading related exceptions. The reason is, as yet, unknown to me. Hope to find out soon.

Tuesday, December 19, 2006

Data Access with Java Persistence API

The Java Persistence API simplifies the entity persistence model and adds new capabilities to the Java EE platform technology, it is the standard API for the management of persistence and object/relational mapping in Java EE 5. In this post, I will give a simple example of how to use JPA from a web application. I used BEA Kodo 4.1 and Weblogic application server 10.0 techinical preview. Follow these steps to run the example
  1. Download BEA Kodo 4.1 from here. You will also need to have a license file to use Kodo. The license file can be downloaded from here. Copy the license file into your classpath.

  2. You can download the Weblogic Application Server 10 TP from BEA.
Example Code
  1. Start with a "Dynamic Web Project" in Eclipse.
  2. Create the Persistence Class (Entity): The source code for the entity class is shown below:
    package beans;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name = "EMP")
    public class Employee {

    private long empId;

    private String empName;

    private String empJob;

    private long empSal;

    @Id
    @Column(name = "EMPNO")
    public long getEmpId() {
    return empId;
    }

    public void setEmpId(long empId) {
    this.empId = empId;
    }

    @Column(name = "JOB")
    public String getEmpJob() {
    return empJob;
    }

    public void setEmpJob(String empJob) {
    this.empJob = empJob;
    }

    @Column(name = "ENAME")
    public String getEmpName() {
    return empName;
    }

    public void setEmpName(String empName) {
    this.empName = empName;
    }

    @Column(name = "EMPSAL")
    public long getEmpSal() {
    return empSal;
    }

    public void setEmpSal(long empSal) {
    this.empSal = empSal;
    }
    }
    Employee.java
    • The persistence classes, or entities are annotated with the javax.persistence.Entity annotation.
    • It is required to have a public/protected no-arg constructor.
    • Neither Entity class nor any of it's properties are to be declared final.
    • The @Id annotation defines a particular field as a primary key.
    • The properties of the Entity class are mapped to the Columns of the database with the @Column annotation.
  3. Create the Data Access Object: The code for the Data access object is shown below
    public class DAO {
    private static int pageSize = 3;
    private EntityManagerFactory emf;

    private static DAO dao = new DAO();
    private DAO() {
    }
    public static DAO getInstance() {
    return dao;
    }

    public List getData(int pageNumber) {

    EntityManager em = null;
    try {
    System.out.println(emf);
    em = emf.createEntityManager();

    Query query = em.createQuery("SELECT e FROM Employee e");
    query = query.setFirstResult(pageSize * (pageNumber - 1));
    query.setMaxResults(pageSize);
    List results = query.getResultList();
    return results;

    } catch (Exception ex) {
    ex.printStackTrace();
    return null;
    } finally {
    em.close();
    }

    }

    public void setEmf(EntityManagerFactory emf) {
    dao.emf = emf;
    }
    }
    DAO.java
    • The DAO class uses the EntityManagerFactory injected by the ContextListener on initialization, to obtain an instance of the EntityManager which is used to create Queries.
  4. Create a Context Listener: JPA annotations can be used to inject the EntityManager and the EntityManagerFactory into the Managed objects. The persistence annotations are supported only with managed classes such as servlet, filters, listeners, etc. You cannot use annotations with regular POJOs. To that end, I have created a Context Listener, which will be injected with the and which inturn injects the EntityManagerFactoryEntityManagerFactory into the DAO class.
    public class ContextListener implements ServletContextListener {

    @PersistenceUnit(unitName="emp")
    EntityManagerFactory emf;

    public void contextDestroyed(ServletContextEvent arg0) {
    }
    public void contextInitialized(ServletContextEvent arg0) {
    // EntityManagerFactory emf = Persistence.createEntityManagerFactory ("emp");
    DAO dao = DAO.getInstance();
    System.out.println("EMF : " + emf);
    dao.setEmf(emf);
    }
    }
    ContextListener.java

    The commented out line in the ContextListener class shown below
    EntityManagerFactory emf = Persistence.createEntityManagerFactory ("emp");
    is another way to obtain an instance of the EntityManagerFactory.

  5. Update Web.xml: By default, when you create a "dynamic web project" in eclipse as of today, the web.xml file will be prepared for J2EE 1.4, you have to update it to Java EE5 (note the web-app declaration below). The application server will not inject the EntityManagerFactory into the ContextListener if the Web-App version is not set to 2.5, and you will get a NullPointerException. You also have to add the ContextListener to the web.xml file.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
    version="2.5"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>JPATest</display-name>
    <listener>
    <listener-class>listeners.ContextListener</listener-class>
    </listener>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>
    web.xml
  6. Create the JSP file: The JSP file here is similar to the previous JSP files used for the Paging examples. The only difference being the use of the DAO.getInstance() method. This change was made to be able to inject the EntityManagerFactory into the DAO object.
    <jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:c="urn:jsptld:http://java.sun.com/jsp/jstl/core">
    <jsp:directive.page contentType="text/html; charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="css/screen.css" />
    <jsp:scriptlet>
    int pageNumber=1;
    if(request.getParameter("page") != null) {
    session.setAttribute("page", request.getParameter("page"));
    pageNumber = Integer.parseInt(request.getParameter("page"));
    } else {
    session.setAttribute("page", "1");
    }
    String nextPage = (pageNumber +1) + "";
    session.setAttribute( "EmpList", data.DAO.getInstance().getData(pageNumber));
    System.out.println(((java.util.List)session.getAttribute("EmpList")).size());
    String myUrl = "pagingEmp.jsp?page=" + nextPage;
    System.out.println(myUrl);

    pageContext.setAttribute("myUrl", myUrl);
    </jsp:scriptlet>
    <h2 align="center">Emp Table with Display tag</h2>
    <jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean>
    <table>
    <tr>
    <th>Employee Id</th>
    <th>Name</th>
    <th>Job</th>
    <th>Salary</th>
    </tr>
    <c:forEach items="${EmpList}" var="emp" begin="0" end="10">
    <tr>
    <td><c:out value="${emp.empId}"></c:out></td>
    <td><c:out value="${emp.empName}"></c:out></td>
    <td><c:out value="${emp.empJob}"></c:out></td>
    <td><c:out value="${emp.empSal}"></c:out></td>
    </tr>
    </c:forEach>

    <tr>
    <td colspan="2"></td>
    <td colspan="2"><a href="${pageScope.myUrl}">nextPage</a></td>
    </tr>
    </table>
    </jsp:root>
    pagingEmp.jsp
  7. The persistence Unit definition: A persistence unit defines a set of entity classes managed by a single EntityManager. This set of entity classes represents the data contained within a single data store.
    Persistence units are defined in the persistence.xml configuration file. The persistence.xml file is to be placed in the CLASSPATH/META-INF/ directory. Here is the persistence unit I defined in the example
    <?xml version="1.0" encoding="ISO-8859-1" ?>

    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="emp" transaction-type="JTA">
    <class>beans.Employee</class>
    <properties>
    <property name="kodo.ConnectionURL" value="jdbc:oracle:thin:@localhost:1521/orcl" />
    <property name="kodo.ConnectionDriverName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="kodo.ConnectionUserName" value="scott" />
    <property name="kodo.ConnectionPassword" value="tiger" />
    <property name="kodo.jdbc.SynchronizeMappings" value="refresh" />
    <property name="kodo.Log" value="DefaultLevel=WARN, SQL=WARN, Runtime=INFO, Tool=INFO" />
    </properties>
    </persistence-unit>

    </persistence>
    src/META-INF/persistence.xml
  8. The Jar files: Make sure that you include the following JAR files from the KODO download
    • serp.jar
    • openjpa.jar
    • ojdbc14.jar
    • kodo.jar
    • jta-spec1_0_1.jar
    • jpa.jar
    • jdo.jar
    • commons-collections-3.2.jar
    • commons-pool-1.3.jar
    • commons-lang-2.1.jar
    • jca1.0.jar
    You will also need the jar files for JSTL etc...
Resources: This post described the implementation of JPA on Weblogic, here are a few resources that help you to implement JPA in different environments

Thursday, December 14, 2006

Paging in JSP with Hibernate

In the past, I had a few posts on how to implement pagination using displaytag(1, 2). That solution is feasible only with small result sets, the reason being that we will have the entire result set in memory (also called cache based paging). If the result set is large, then having the entire result set in memory will not be feasible. With large result sets, you cannot afford to have them in memory. In such case, you have to fetch a chunk of data at a time (query based paging). The down side of using query based paging, is that there will be multiple calls to the database for multiple page requests. In this post, I will describe how to implement simple query based caching solution, using Hibernate and a simple JSP. Time permitting, I will soon post a hybrid of cache based and query based paging example. Here is the code for implementing simple paging using a JSP and Hibernate:
  1. Download the latest version of hibernate from hibernate.org, and include all the required jars in your classpath.
  2. Hibernate configuration
    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
    <session-factory>
    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property>
    <property name="connection.username">scott</property>
    <property name="connection.password">tiger</property>
    <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="beans/Employee.hbm.xml" />
    </session-factory>
    </hibernate-configuration>
    hibernate.cfg.xml
  3. The Employee bean class to hold the data
    public class Employee {
    public long empId;
    public String empName;
    public String empJob;
    public long empSal;
    public long getEmpId() {
    return empId;
    }
    public void setEmpId(long empId) {
    this.empId = empId;
    }
    public String getEmpJob() {
    return empJob;
    }
    public void setEmpJob(String empJob) {
    this.empJob = empJob;
    }
    public String getEmpName() {
    return empName;
    }
    public void setEmpName(String empName) {
    this.empName = empName;
    }
    public long getEmpSal() {
    return empSal;
    }
    public void setEmpSal(long empSal) {
    this.empSal = empSal;
    }
    }
    Employee.java
  4. The Employee Mapping file: This listing of the Data Access Object uses the setMaxResults, and setFirstResult method of the Query object to extract the appropriate set of results for each page.
    <?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.Employee" table="Emp">
    <id name="empId" column="EMPNO" type="long">
    <generator class="native"/>
    </id>
    <property name="empName" column="ENAME" />
    <property name="empJob" column="JOB" />
    <property name="empSal" column="SAL" type="long"/>
    </class>
    </hibernate-mapping>
    Employee.hbm.xml
  5. The Data Access Object
    public class DAO {
    private static int pageSize = 3;
    public static List getData(int pageNumber) {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.getCurrentSession();
    List result = null;
    try {
    session.beginTransaction();
    Query query = session.createQuery("from Employee");
    query = query.setFirstResult(pageSize * (pageNumber - 1));
    query.setMaxResults(pageSize);
    result = query.list();
    session.getTransaction().commit();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }
    }
    DAO.java
  6. The JSP
    <jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:c="urn:jsptld:http://java.sun.com/jsp/jstl/core">
    <jsp:directive.page contentType="text/html; charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="css/screen.css" />
    <jsp:scriptlet>
    int pageNumber=1;
    if(request.getParameter("page") != null) {
    session.setAttribute("page", request.getParameter("page"));
    pageNumber = Integer.parseInt(request.getParameter("page"));
    } else {
    session.setAttribute("page", "1");
    }
    String nextPage = (pageNumber +1) + "";
    session.setAttribute( "EmpList", data.DAO.getData(pageNumber));
    System.out.println(((java.util.List)session.getAttribute("EmpList")).size());
    String myUrl = "pagingEmp.jsp?page=" + nextPage;
    System.out.println(myUrl);

    pageContext.setAttribute("myUrl", myUrl);
    </jsp:scriptlet>
    <h2 align="center">Emp Table with Display tag</h2>
    <jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean>
    <table>
    <tr>
    <th>Employee Id</th>
    <th>Name</th>
    <th>Job</th>
    <th>Salary</th>
    </tr>
    <c:forEach items="${EmpList}" var="emp" begin="0" end="10">
    <tr>
    <td><c:out value="${emp.empId}"></c:out></td>
    <td><c:out value="${emp.empName}"></c:out></td>
    <td><c:out value="${emp.empJob}"></c:out></td>
    <td><c:out value="${emp.empSal}"></c:out></td>
    </tr>
    </c:forEach>

    <tr>
    <td colspan="2"></td>
    <td colspan="2"><a href="${pageScope.myUrl}">nextPage</a></td>
    </tr>
    </table>
    </jsp:root>
    pagingEmp.jsp

    This JSP uses the DAO class to retrieve the Employee information from the database. The page number is passed as a parameter to the DAO. Notice that I did not implement the "previous" page, but it is similar to next. I assumed that we do not know the number of results for this example.

Tuesday, December 05, 2006

Download Oracle technology network's CD

OTN's "Greatest Hits" CD is a compilation of the most popular technical articles, software downloads, podcasts, sample code, and documentation published on OTN in 2006. Available in Zip and ISO formats.

Data Access with Spring and Struts: Part 2

Part 1 of "Data Access with Spring and struts" described how to make a struts application ready to use spring. In this post, we will see how to implement spring data access.
  1. Create a RowMapper: A row mapper is used to map a single row in the ResultSet to any object. The iteration through the result set is taken care of by the JdbcTemplate class.
    public class EmpMapper implements RowMapper {
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
    int empNo = rs.getInt(1);
    String empName = rs.getString(2);
    String empJob = rs.getString(3);
    long salary = rs.getLong(4);
    Employee emp = new Employee();
    emp.setEmpId(empNo);
    emp.setEmpJob(empJob);
    emp.setEmpSal(salary);
    emp.setEmpName(empName);
    return emp;
    }
    }
    EmpMapper.java
  2. Create the Data Access Object: The Data access object uses spring's JdbcTemplate class to query the database. The JdbcTemplate class helps separate the static parts of JDBC DAO code by performing
    the common boilerplate tasks:
    • Retrieves connections from the datasource.
    • Prepares statement object.
    • Executes SQL CRUD operations.
    • Iterates over result sets and populates the results in standard collection objects.
    • Handles SQLException and translates it into a more explicit exception in the spring exception hierarchy.
    public class DAO extends JdbcDaoSupport {
    public long empId;
    public String empName;
    public String empJob;
    public long empSal;
    public String SQL = "SELECT EMPNO, ENAME, JOB, SAL " + "FROM EMP WHERE SAL >= ?";
    public List getData(long minSal) {
    Long params[] = { minSal };
    JdbcTemplate daoTmplt = getJdbcTemplate();
    return daoTmplt.query(SQL, params, new EmpMapper());
    }
    }
    DAO.java

    Note that the DAO class has to extend JdbcDaoSupport, which defines the getJdbcTemplate() method.
  3. Create the Business Interface: The business interface class acts as a simple facade to the DAO layer.
    public class BusinessInterface {
    DAO empDAO;
    public List getData(long minSal){
    List empList = empDAO.getData(minSal);
    return empList;
    }
    public void setDao(DAO empDAO){
    this.empDAO = empDAO;
    }
    }
    BusinessInterface.java
  4. Add the Action class, Business Interface and DAO to Spring
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
    <bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName">
    <value>oracle.jdbc.driver.OracleDriver</value>
    </property>
    <property name="url">
    <value>jdbc:oracle:thin:@localhost:1521:orcl</value>
    </property>
    <property name="username">
    <value>scott</value>
    </property>
    <property name="password">
    <value>tiger</value>
    </property>
    </bean>

    <!-- Configure DAO -->
    <bean id="empDao" class="data.DAO">
    <property name="dataSource">
    <ref bean="dataSource"></ref>
    </property>
    </bean>
    <!-- Configure Business Service -->
    <bean id="businessInterface" class="business.BusinessInterface">
    <property name="dao">
    <ref bean="empDao"></ref>
    </property>
    </bean>
    <bean name="/search" class="actions.SearchAction">
    <property name="businessInterface">
    <ref bean="businessInterface" />
    </property>
    </bean>
    </beans>
    WEB-INF/applicationContext.xml

    Note that SearchAction is defined here, instead of in the struts-config.xml. The bean name "/search" is used to as a link between this file and struts-config.xml.

  5. Create the Sorter class: This is used in the JSP for sorting the result list.
    public class Sorter {
    public static List sort(List list, String sortBy) {
    Comparator comp = getComparator(sortBy);
    Collections.sort(list, comp);
    return list;
    }

    private static Comparator getComparator(String sortBy) {
    System.out.println("Sort by : " + sortBy);
    if (sortBy == null) {
    return new NameComparator();
    }
    if (sortBy.equals("empName"))
    return new NameComparator();
    if (sortBy.equals("empId"))
    return new IdComparator();
    if (sortBy.equals("empSal"))
    return new SalComparator();
    if (sortBy.equals("empJob"))
    return new JobComparator();

    return null;

    }

    private static class NameComparator implements Comparator {
    public int compare(Object emp1, Object emp2) {
    Employee employee1 = (Employee) emp1;
    Employee employee2 = (Employee) emp2;
    return employee1.getEmpName().compareTo(employee2.getEmpName());
    }
    }

    private static class IdComparator implements Comparator {
    public int compare(Object emp1, Object emp2) {
    Employee employee1 = (Employee) emp1;
    Employee employee2 = (Employee) emp2;
    return new Long(employee1.getEmpId()).compareTo(new Long(employee2.getEmpId()));
    }
    }

    private static class SalComparator implements Comparator {
    public int compare(Object emp1, Object emp2) {
    Employee employee1 = (Employee) emp1;
    Employee employee2 = (Employee) emp2;
    return new Long(employee1.getEmpSal()).compareTo(new Long(employee2.getEmpSal()));
    }
    }

    private static class JobComparator implements Comparator {
    public int compare(Object emp1, Object emp2) {
    Employee employee1 = (Employee) emp1;
    Employee employee2 = (Employee) emp2;
    return employee1.getEmpJob().compareTo(employee2.getEmpJob());
    }
    }
    }
    Sorter.java
  6. Create the Value object: The Employee.java bean used in the row mapper is shown below.
    public class Employee {
    public long empId;
    public String empName;
    public String empJob;
    public long empSal;
    public long getEmpId() {
    return empId;
    }
    public void setEmpId(long empId) {
    this.empId = empId;
    }
    public String getEmpJob() {
    return empJob;
    }
    public void setEmpJob(String empJob) {
    this.empJob = empJob;
    }
    public String getEmpName() {
    return empName;
    }
    public void setEmpName(String empName) {
    this.empName = empName;
    }
    public long getEmpSal() {
    return empSal;
    }
    public void setEmpSal(long empSal) {
    this.empSal = empSal;
    }
    }
    Employee.java
REQUIREMENTS
  1. JAR Files: In order for you to run this example, you must have the following jar files in your class path: displaytag-1.1.jar || commons-chain-1.1.jar || commons-collections.jar || commons-dbcp.jar || commons-digester-1.6.jar || commons-lang.jar || commons-logging.jar || commons-pool-1.3.jar || commons-validator-1.3.0.jar || commons-beanutils.jar || displaytag-export-poi-1.1.jar || jta.jar || ojdbc14.jar || oro-2.0.8.jar || spring.jar || struts-core-1.3.5.jar || struts-taglib-1.3.5.jar || struts-tiles-1.3.5.jar || xml-apis.jar
  2. Tomcat Server
  3. Java 5.0
  4. A log4j configuration file.

Popular Posts