December 31, 2011

Spring - Hibernate framework Integration - Hello World Example

0) To proceed with this example, complete the Spring Hello World Example and the Hibernate Hello World Example

1) Put 2 jar files from the Apache Commons collection in the WebContent/WEB-INF/lib folder of the web application - download the jars from this link

2) Add the following elements to the Spring configuration file, applicationContext.xml
Integrating Spring with Hibernate results in the hibernate.cfg.xml becoming obsolete - the configuration in hibernate.cfg.xml is now put in the applicationContext.xml

Configuration for DataSource (Database Connection properties)

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
   <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
   <property name="username" value="system" />
   <property name="password" value="system" />
</bean>

Configuration for Hibernate (of hibernate.cfg.xml)


<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="dataSource" ref="dataSource"/>
   <property name="mappingResources">
      <list>
         <value>info/icontraining/hibernate/Message.hbm.xml</value>
      </list>
   </property>
   <property name="hibernateProperties">
      <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
      </props>
   </property>
</bean>

Configuration for HibernateTemplate, DAOs, etc.

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
   <property name="sessionFactory" ref="sessionFactory" />
</bean>
 
<bean id="myDao" class="info.icontraining.dao.MyDAO">
   <property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>


3) Create a MyDAO.java class in the src folder of the web application - this class does the actual persistence

package info.icontraining.dao;

import java.util.List;
import info.icontraining.hibernate.Message;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class MyDAO {

   private HibernateTemplate hibernateTemplate;
 
   public void setHibernateTemplate(HibernateTemplate template) {
      this.hibernateTemplate = template;
   }
 
   public void saveData(String str) {
      Message message1 = new Message(str);
      hibernateTemplate.save(message1);
   }

   public int retrieveData() {
      List<Message> messages = hibernateTemplate.find("from Message as m order by m.text asc");
      return messages.size();
   } 
}


4) Create a client JSP - springHibernate.jsp - in the WebContent folder of the web application


<%@ page  import="org.springframework.context.*,org.springframework.web.context.*,info.icontraining.spring.*,info.icontraining.dao.*"%>
<html>
<body>

<% 
 ApplicationContext factory = 
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 MyDAO mydao = (MyDAO)factory.getBean("myDao");
 mydao.saveData("Spring Hibernate");
 
 int numMessages = mydao.retrieveData();
%>
 
<%= numMessages + " messages found." %>

</body>
</html>

5) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/springHibernate.jsp

Log into Oracle Database and check the contents of the appropriate table

Spring Bean Scope Demo - Prototype & Singleton

1) Create 2 beans - PrototypeBean.java & SingletonBean.java - in the src folder of the web application

package info.icontraining.spring;

public class PrototypeBean {
   private int i;
 
   public PrototypeBean() {
      i = 3;
   }
 
   public void changeValue() {
      i = 5;
   }
 
   public int getValue() {
      return i;
   }
}



package info.icontraining.spring;

public class SingletonBean {

   private int i;
 
   public SingletonBean() {
      i = 3;
   }
 
   public void changeValue() {
      i = 5;
   }
 
   public int getValue() {
      return i;
   } 
}

2) Configure both beans in the WebContent/WEB-INF/applicationContext.xml file - the PrototypeBean bean is configured with the scope attribute set to 'prototype'

<bean id="singleton" class="info.icontraining.spring.SingletonBean" />
 
<bean id="prototype" class="info.icontraining.spring.PrototypeBean" scope="prototype" />

3) Create a client JSP - singletonPrototypeDemo.jsp - in the WebContent folder of the web application

<%@ page  import="org.springframework.context.*,org.springframework.web.context.*,info.icontraining.spring.*"%>
<html>
<body>

 <% 
 ApplicationContext factory = 
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 SingletonBean s1 = (SingletonBean)factory.getBean("singleton");
 s1.changeValue();
 
 SingletonBean s2 = (SingletonBean)factory.getBean("singleton"); 
 %>
 
 <%= "SingletonBean on Reference-1 after changing value = " + s1.getValue() %><br/>
 <%= "SingletonBean on Reference-2 without changing value = " + s2.getValue() %>

<br/><br/>

<% 
 PrototypeBean p1 = (PrototypeBean)factory.getBean("prototype");
 p1.changeValue();
 
 PrototypeBean p2 = (PrototypeBean)factory.getBean("prototype"); 
 %>

 <%= "PrototypeBean on Reference-1 after changing value = " + p1.getValue() %><br/>
 <%= "PrototypeBean on Reference-2 without changing value = " + p2.getValue() %>

</body>
</html>

4) Test the example with the following URL in the browser

http://localhost:8080/WebAppName/singletonPrototypeDemo.jsp

Breaking a large applicationContext.xml configuration file into multiple files

0) Complete the Spring Framework Hello World example at this link

1) Create a new configuration file - applicationContext2.xml - in the WebContent/WEB-INF folder of the web application. Make sure that the root <beans> element is the same as in the applicationContext.xml

Move the <bean> configuration for the greetingService bean to the new configuration file and delete it from the applicationContext.xml

2) Modify the configuration in the web.xml by adding the new configuration file name, as follows,

<context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/applicationContext.xml /WEB-INF/applicationContext2.xml</param-value>
  </context-param>

3) Test the Hello World example as in the Hello World example

Initializing, Destroying Spring Beans & instantiating a Spring Bean through a factory method

1) Create an interface - InitDestroyDemo.java - in the src folder of the web application

package info.icontraining.spring;

public interface InitDestroyDemo {
   public void businessMethod();
}


2) Create a Spring Bean that implements the interface - InitDestroyDemoImpl.java - in the src folder of the web application

package info.icontraining.spring;

public class InitDestroyDemoImpl implements InitDestroyDemo {

   private InitDestroyDemoImpl() { }
 
   public void myInitMethod() {
      System.out.println("Inside Init Method of Spring Bean");
   }
 
   public void businessMethod() {
      System.out.println("Inside Business Method of Spring Bean");
   }
 
   public void myDestroyMethod() {
      System.out.println("Inside Destroy Method of Spring Bean");
   }
 
   public static InitDestroyDemo getInstance() {
      return new InitDestroyDemoImpl();
   }
}


3) Configure the Spring Bean in the WebContent/WEB-INF/applicationContext.xml file

The bean is configured with an initializing method using the init-method attribute, with a destroying method using the destroy-method attribute.

The constructor of the bean is made private, and instantiation is instead done through a static factory method, getInstance() - this is configured using the factory-method attribute

<bean id="initDestroyDemo" class="info.icontraining.spring.InitDestroyDemoImpl" init-method="myInitMethod" destroy-method="myDestroyMethod" factory-method="getInstance" />


4) Create a client JSP - springInitDestroy.jsp - in the WebContent folder of the web application

<%@ page  import="org.springframework.context.*,org.springframework.web.context.*,info.icontraining.spring.*"%>
<html>
<body>

View output on Server console

 <% 
 ApplicationContext factory = 
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 InitDestroyDemo test = (InitDestroyDemo)factory.getBean("initDestroyDemo");
 test.businessMethod();
 
 %>
</body>
</html>


5) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/springInitDestroy.jsp