Showing posts with label sample code. Show all posts
Showing posts with label sample code. Show all posts

Sunday, 8 May 2011

Integrating Spring and Hibernate

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.

 

Prerequisite jars for this example

  • 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

Example Code

1. Create the entity bean: The bean here represents a simple stock quote

package com.vaani.entity;

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;
}
}


2. Create a Hibernate Mapping file (hbm) for the entity:


<?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="com.vaani.entity.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>


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. Create the service class: The service class simply acts as an intermediary between the client and the DAO classes.


package com.vaani.springhibernate;

import com.vaani.entity.StockQuoteBean;
import com.vaani.hibernate.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());
}

}


4. The DAO interface:


package com.vaani.hibernate.dao;

import com.vaani.entity.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);
}


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.


Using HibernateTemplate


package com.vaani.hibernate.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;
}



}

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.

 

Using HibernateDaoSupport

package com.vaani.hibernate.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);
}

}

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="com.vaani.hibernate.dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

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

<bean id="portfolioService" class="com.vaani.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>



  • 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

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 com.vaani.entity.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);
}


}



 

Thursday, 17 March 2011

Spring IOC or DI - Reducing coupling

In Spring, the Inversion of Control (IoC) principle is implemented using the Dependency Injection (DI) design pattern. But note that In spring framework both terms are used interchangeably. Let's understand dependency injection with the help of an example.

Example of Tight Coupling

The QuizMater interface exposes the popQuestion() method. To keep things simple, our QuizMaster will generate only one question.

Getting the interface ready
QuizMaster.java
package com.vaani.bean.quizmaster;

public interface QuizMaster {

public String popQuestion();
}

Getting the implementations ready
The StrutsQuizMaster and the SpringQuizMaster class implements QuizMaster interface and they generate questions related to struts and spring respectively.
StrutsQuizMaster.java 
public class StrutsQuizMaster implements QuizMaster {

@Override
public String popQuestion() {

return "Are you new to Struts?";

}

}
SpringQuizMaster.java
public class SpringQuizMaster implements QuizMaster {

@Override
public String popQuestion() {
return "Are you new to Spring?";
}
}
We have a QuizMasterService class that displays the question to the user. The QuizMasterService class holds reference to the QuizMaster.
public class QuizMasterService {

private QuizMaster quizMaster = new SpringQuizMaster();

public void askQuestion()
{
System.out.println(quizMaster.popQuestion());
}
}
Finally we create the QuizProgram class to conduct quiz.
public class QuizProgram {

public static void main(String[] args) {
QuizMasterService quizMasterService = new QuizMasterService();
quizMasterService.askQuestion();
}

}
As you can see it is pretty simple, here we create an instance of the QuizMasterService class and call the askQuestion() method. When you run the program as expected "Are you new to Spring?" gets printed in the console.
Let's have a look at the class diagram of this example. The green arrows indicate generalization and the blue arrows indicates association.


spring dependency injection1

As you can see this architecture is tightly coupled. We create an instance of the QuizMaster in the QuizMasterService class in the following way.
private QuizMaster quizMaster = new SpringQuizMaster();
To make our quiz master Struts genius we need to make modifications to the QuizMasterService class like this.
private QuizMaster quizMaster = new StrutsQuizMaster();

So it is tightly coupled. Also we have to hard-code the stuff here. This is not good for development environments, because we have again and again change code for some simple stuff. Now lets see how we can avoid this by using the Dependency Injection design pattern.


How to reduce tight coupling here?
So the solution we can think of is either use factory pattern. But still we will see another method called DI or dependency injection is far better than factory pattern.


Reducing coupling via Factory Pattern


Now one solution to this is factory pattern.We can make a factory class, which produces all beans for us.
Beans in the example there were SpringQuizMaster and StrutsQuizMaster.
First of all we can create the factory:

public class QuizMasterFactory {
public static QuizMaster getQuizMaster(String subject)
{
if("Spring".equals(subject))
return new SpringQuizMaster();
else if("Struts".equals(subject))
return new StrutsQuizMaster();
else
throw new IllegalArgumentException("No subject exists with name "+subject);
}
}

Now you should get your service ready.And in service we can simply do this:
public class QuizMasterServiceFromFactory {

QuizMaster quizMaster;

public void setQuizMaster(QuizMaster quizMaster) {
this.quizMaster = quizMaster;
}

public void askQuestion()
{
System.out.println(quizMaster.popQuestion());
}
}
Now in main method we can do:

public static void main(String[] args) {
QuizMaster quizMaster = QuizMasterFactory.getQuizMaster("Spring");
QuizMasterServiceFromFactory quizMasterService = new QuizMasterServiceFromFactory();
quizMasterService.setQuizMaster(quizMaster);

quizMasterService.askQuestion();
}

But still if there is still new requirement, to add other beans like HibernateQuizMaster...we have to edit  this factory class as well, so still have to build and all that stuff. So here comes spring in picture.
The Spring framework provides prowerful container to manage the components. The container is based on the Inversion of Control (IoC) principle and can be implemented by using the Dependency Injection (DI) design pattern. Here the component only needs to choose a way to accept the resources and the container will deliver the resource to the components.
So now we do this by spring to reduce coupling.


Spring Method or reducing coupling via DI or IOC


The value for the QuizMaster will be set using the setQuizMaster() method. The QuizMaster object is never instantiated in the QuizMasterService class, but still we access it. Usually this will throw a NullPointerException, but here the container will instantiate the object for us, so it works fine.
Now consider this service, which refer these beans, but have now nothing to worry about how to create beans :


public class QuizMasterServiceSpring {

QuizMaster quizMaster;

public void setQuizMaster(QuizMaster quizMaster) {
this.quizMaster = quizMaster;
}

public void askQuestion()
{
System.out.println(quizMaster.popQuestion());
}
}

 


After making all the changes, the class diagram of the example look like this.

dependency injection reduction spring


The container comes into picture and it helps in injecting the dependancies.
The bean configuration is done in the beans.xml file.

<?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="springQuizMaster" class="com.vaani.spring.quizmaster.SpringQuizMaster"></bean>
<bean id="strutsQuizMaster" class="com.vaani.spring.quizmaster.StrutsQuizMaster"></bean>
<bean id="quizMasterService" class="com.vaani.spring.quizmaster.QuizMasterService">
<property name="quizMaster">
<ref local="springQuizMaster"/>
</property>
</bean>

</beans>

We define each bean using the bean tag. The id attribute of the bean tag gives a logical name to the bean and the class attribute represents the actual bean class. The property tag is used to refer the property of the bean. To inject a bean using the setter injection you need to use the ref tag.
Here a reference of SpringQuizMaster is injected to the QuizMaster bean. When we execute this example, "Are you new to Spring?" gets printed in the console.
To make our QuizMaster ask questions related to Struts, the only change we need to do is, to change the bean reference in the ref tag.

<bean id="quizMasterService" class="com.vaani.spring.quizmaster.QuizMasterService">
<property name="quizMaster">
<ref local="strutsQuizMaster"/>
</property>
</bean>


In this way the Dependency Injection helps in reducing the coupling between the components.
To execute this example add the following jar files to the classpath.


  • antlr-runtime-3.0
  • commons-logging-1.0.4
  • org.springframework.asm-3.0.0.M3
  • org.springframework.beans-3.0.0.M3
  • org.springframework.context-3.0.0.M3
  • org.springframework.context.support-3.0.0.M3
  • org.springframework.core-3.0.0.M3
  • org.springframework.expression-3.0.0.M3

So instead of changing code in java, we have to change the xml only, whenever the need be. Also from the spring example, it was clear why we call it inversion of control. Because we needed beans in the service, we have to first define and initiate these beans, and then give it to service class. But beauty of spring is that we don't have to worry about how spring will initialize these beans. We can provide beans in any order and spring will determine how to initialize those. See other dependency injection frameworks.

Download the Source


You can download the source code with "Tight coupled" Quizmaster here.

You can download the source code of Factory method pattern solving coupling problem here.

Also you can finally download the whole example with spring from here.