Pages

Tuesday, August 3, 2010

Spring - Simple Form Controller

index.jsp
When the first request comes to this jsp, its simply redirect to the request to userRegistration.htm

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% response.sendRedirect("userRegistration.htm"); %>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
In the above web.xml file we have declared the url-pattern is *.htm, so it checks any request having *.htm, if any request having *.htm then it checks the corresponding servlet class, In our case its DispatcherServlet. Then Container looks the servlet name declared in web.xml accordingly it invokes the (servlet name in web.xml)-serlvet.xml file. In our case its dispatcher-servlet.xml file


dispatcher-servlet.xml
In the above web.xml file we have declared the servlet name as dispatcher, so our spring config file name should be dispatcher-servlet.xml only

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp" />
<bean name="/userRegistration.htm" class="com.UserController"
p:formView="userForm" p:successView="userSuccess" />
</beans>




As you can see, we use "p" namespace here. The "p" namespace is simple and easy to use. Using "p" namespace the properties can be supplied using attributes, rather than elements.
For injecting the simple types we use property name in the "p" namespace and for injecting references we add "-ref" suffix to it. For example we use p:formView for injecting the form view property andp:userService-ref for injecting the user service.
Our request having the /userRegistration.htm, So it invokes the UserContrller. before that it checks the formView, Here it is userForm then it invokes the userForm.jsp first.
userForm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"



pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
</head>
<body>
<form:form method="POST" commandName="user">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M"  /> 
<form:radiobutton path="gender" value="F"  /></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form:form>
</body>
</html>
Here the path attribute is used to bind the form fields to the domain object. Here we use the HTTP POST method to submit the form. Inorder to bind the form fields to the domain object successfully the command object should be set to the same name in the jsp page and the controller class. To set the command object name in the jsp page, use the commandName attribute of the form tag.

UserController.java
package com;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class UserController extends SimpleFormController {
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
return new ModelAndView("userSuccess","user",user);
}
}
Here we extend the UserController from SimpleFormController, this makes the controller class capable of handling forms. Usually a form will be associated with a particular domain object, in our case it is the Userclass. In Spring this domain object is called command object by default. To refer the command object in the jsp page you need to set the command class using the setCommandClass() method in the constructor. Let say the User class has a name property, and to refer this in the jsp page you will use "command.name". You can also change this name by using the setCommandName() method. Here we set the name to user, so to access the user name in the jsp page we use "user.name".
You need to have a method to handle the form when the form is submitted, here the onSubmit()method is used for this purpose. The onSubmit() method has access to the command object, we first typecast the command object to User (our domain object) and then to register the user we call the add() method of the service class and finally return the ModelandView object.
All the forms field values will be submitted as Strings to the form controller. Spring has several pre registered property editors to convert the String values to common data types. Incase you have a custom data type you need to create custom property editors to handle them.
User.java
package com;
public class User {
private String name;
private String password;
private String gender;
private String aboutYou;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
}
userSuccess.jsp
we have declared the successView in the dispatcher-servlet.xml as userSuccess, So it invokes the userSuccess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success Page</title>
</head>
<body>
User Details
<hr>
User Name   : ${user.name} <br/>
Gender      : ${user.gender} <br/>
About You   : ${user.aboutYou} <br/>
</body>
</html>











Monday, August 2, 2010

SPRING WEB MVC

Features of Spring Web MVC
Spring's web module provides a wealth of unique web support features, including:
  • Clear separation of roles - controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized object.
  • Powerful and straightforward configuration of both framework and application classes as JavaBeans, including easy referencing across contexts, such as from web controllers to business objects and validators.
  • Adaptability, non-intrusiveness. Use whatever controller subclass you need (plain, command, form, wizard, multi-action, or a custom one) for a given scenario instead of deriving from a single controller for everything.
  • Reusable business code - no need for duplication. You can use existing business objects as command or form objects instead of mirroring them in order to extend a particular framework base class.
  • Customizable binding and validation - type mismatches as application-level validation errors that keep the offending value, localized date and number binding, etc instead of String-only form objects with manual parsing and conversion to business objects.
  • Customizable handler mapping and view resolution - handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. This is more flexible than some web MVC frameworks which mandate a particular technique.
  • Flexible model transfer - model transfer via a name/value Map supports easy integration with any view technology.
  • Customizable locale and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, etc.
  • A simple yet powerful JSP tag library known as the Spring tag library that provides support for features such as data binding and themes. The custom tags allow for maximum flexibility in terms of markup code. For information on the tag library descriptor, see the appendix entitled Appendix D, spring.tld
  • A JSP form tag library, introduced in Spring 2.0, that makes writing forms in JSP pages much easier. For information on the tag library descriptor, see the appendix entitled Appendix E, spring-form.tld
  • Beans whose lifecycle is scoped to the current HTTP request or HTTP Session. This is not a specific feature of Spring MVC itself, but rather of the WebApplicationContext container(s) that Spring MVC uses. These bean scopes are described in detail in the section entitled Section 3.4.4, “The other scopes”

Spring Web MVC Flow
  1. Spring Web MVC is identical to Struts Framework
  2. In every web application framework one front controller must be configured in web.xml file
  3. The purpose of the configuring the front controller in web.xml file is to collect all the HTML form requests into a single servlet class that will manage the flow of execution for any number of HTML form. Hence using this feature instead of writing one servlet class for each HTML form; for the entire application only one single servlet will be configured. We can reduce many servlets with a single servlet.
  4. The front controller class name is org.springframework.web.servlet.DispatcherServlet in spring framework. In struts we have ActionServlet.
  5. And the url-pattern configured for that servlet is *.htm. In struts we have *.do
  6. The intension is every HTML form request want to be submitted to spring web MVC framework must submit action path ends with .htm extension. For instance suppose if a new customer information want to be submitted the HTML form must submit requesting using ./nc.htm
  7. Soon after the request comes to DispatcherServlet, DispatcherServlet reads disp-servet.xml file (Spring files we usually stores with the name web.xml) but in spring web MVC the spring configuration file must be  saved with the servlet name as prefix disp and -servlet.xml as suffix. (disp-serlvet.xml)
  8. In the disp-servlet.xml file the action path is mapped to spring controller class (in spring business logic is called as Contrller class).
  9. DispatcherServlet instantiates Controller class, injects if any dependent objects are required and invokes its handleRequest(HttpServletRequest,HttpServletResponse) method
  10. In spring web MVC the controller class must implement business logic implementation in handleRequest() method.
  11. The function must read all request parameters using HttpServletRequest object.
  12. Stores the record into DB using jdbcTemplate or HibernateTemplate.
  13. After return which JSP/HTML page want to be returned to browser using ModelAndView class object.
  14. ModelAndView class contains the response generated by the spring controller and response view name in a single object.
  15. Soon the ModelAndView object is returned to DispatcherServlet, DispatcherServlet stores the response in request scope and redirect the response view to browser.
  16. The response view retrieves the response from request scope and display's the out put on browser.
Example
The Flow of this application is almost nearby similar or Struts web application framework, except with some minor changes. The changes are FrontController class name is different, Spring config file name is different, the business component must implement the Controller interace, the method name is handleRequest() and return type is ModelAndView.


index.jsp

<html>
  <body>
   <form action="./nc.htm">
   <table>
   <tr>
   <td>Customer ID : </td>
   <td><input type="text" name="id"/></td>
   </tr>
   <tr>
   <td>Customer Name : </td>
   <td><input type="text" name="name"/></td>
    </tr>
    <tr>
   <td>Customer Age : </td>
   <td><input type="text" name="age"/></td>
    </tr>
   </table>
  <tr>
  <input type="submit" name="submit" value="Submit"/>
  </tr>
   </form>
  </body>
</html>


web.xml
<web-app 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">
<servlet>
<servlet-name>disp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
  <servlet>
    <servlet-name>CustomerController</servlet-name>
    <servlet-class>com.CustomerController</servlet-class>
  </servlet>
<servlet-mapping>
<servlet-name>disp</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
  <servlet-mapping>
    <servlet-name>CustomerController</servlet-name>
    <url-pattern>/servlet/CustomerController</url-pattern>
  </servlet-mapping>
 <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

disp-servlet.xml
<?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">
<bean name="/nc.htm" class="com.CustomerController">
</bean>

</beans>

CustomeController.java
package com;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class CustomerController implements Controller {
public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse res) throws Exception {
int id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
int age = Integer.parseInt(req.getParameter("age"));
System.out.println(" Name :: "+ name+ " Age :: "+age);
return new ModelAndView("/success.jsp","id",new Integer(id) );
}
}

Success.jsp
<html>
  <body>
      Customer ID is : <%=(Integer)request.getAttribute("id") %>
     </body>
</html>


Sunday, August 1, 2010

Spring With Hibernate


Spring provides hibernate template and it has many advantages like
  • It removes boiler plate code like getting connection from data source try/catch block for closing connection. So that developer can focus on writing business logic rather then writing boilier plate code every where.
  • Spring hibernateTemplate also throws RunTime exception compared to checkd exception which allows to remove writing try/catch block in each DAO. 
  • It also gives richer template class using which developer can write query code easily. This template class also allows to get session explicitly so if developer wants to get session object and work on it then it's possible.
  • Spring provides support for both hibernate and JDBC Templates.It provides template classes which contains all common code.But JDBC as we all know is not an ORM tool it does not represent rows as objects whereas Hibernate does that.
  • Anyway, sometimes you will need to access directly hibernate objects. For example, Query object has some interesting methods, not accessible in the templete. For such cases, you may use getHibernateTemplate().execute(HibernateCallBack).
  • HibernateCallBack, is just an interface which has a method which will recieve an Hibernate Session object you can operate with (Normally, you will create an inner class)
  • A final advice. If you use some callback function very frequently, just extend the HibernateTemplate, and make a wrapping method for the callback. It is much cleaner than using callbacks everywhere
Spring With Hibernate
As a pre-requisite, let us understand the need for such integration before we actually get into the integration between these two technologies. It is well known that Hibernate is a powerful ORM tool that lies between Application and Database. It enables Application to access data from any database in a platform-independent manner. There is no need for the Application to depend on the low-level JDBC details like managing connection, dealing with statements and result sets. All the necessary details for accessing a particular data source is easily configurable in Xml files. Another good thing is that Hibernate can be coupled well with both J2SE and J2EE Applications.

One of the problem with using Hibernate is that the client Application that accesses the database using Hibernate Framework has to depend on the Hibernate APIs like Configuration, SessionFactory and Session. These objects will continue to get scattered across the code throughout the Application. Moreover, the Application code has to manually maintain and manage these objects. In the case of Spring, the business objects can be highly configurable with the help of IOC Container. In simple words, the state of an object can be externalized from the Application code. It means that now it is possible to use the Hibernate objects as Spring Beans and they can enjoy all the facilities that Spring provides.

Creating Database
 CREATE TABLE `customer` (
  `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `NAME` varchar(100) NOT NULL,
  `AGE` int(10) UNSIGNED NOT NULL,
  PRIMARY KEY (`CUST_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Customer.java
Now let us create a class called Customer for storing the data that are fetched from the Customer table. The class design is such that the column names for the table 'Customer' will be mapped as the variable names in the Java class with the appropriate data type. The complete code listing for the Customer class is as follows,
package com;

public class Customer{
private int id;
private String name;
private int age;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}

customer.hbm.xml

We have created 'customer' table in the database and a corresponding Java class in the Application layer. However, we haven't specified that the 'customer' table should map to the Java class and the column names in the 'customer' table should map to the Java variables in the Customer class. This is where the Hibernate Mapping files comes into picture. Let us have a look at the Hibernate Mapping file,

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.Customer" table="CUSTOMER" schema="MYBLOG">
        <id name="id" type="java.lang.Long">
            <column name="ID" />
            <generator class="assigned"></generator>
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="20" />
        </property>
        <property name="age" type="java.lang.Long">
            <column name="AGE" />
        </property>
    </class>
</hibernate-mapping>

Note that the Mapping file is an Xml file and its name is Customer.hbm.xml. The portion of the string 'hbm' in the mapping file stands for hibernate Mapping File. Although it is not necessary to follow this convention, it will be easy to figure what type of xml file is this, just by looking at the extension. Xml conforms to a well-defined DTD, the hibernate-mappings-3.0.dtd.

The root element for the mapping file is the hibernate-mapping tag which can define one or more mappings, following which we have the class tag which defines a mapping between the database table name and the Java class. The 'name' attribute must point to a fully qualified Java class name whereas the table attribte must point to the database table.

The next series of tags define the mapping definition of the column names against its Java variables counterparts. The 'id' tag defines an identifier for a row and it is commonly used as a primary key column. The property tag has an attribute called 'name' which points to the Java variable name, following which is the name of the column in the database table to which it maps to.

applicationContext.xml
This section deals with configuring the various information needed for the Spring Framework. In Spring, all the business objects are configured in Xml file and the configured business objects are called Spring Beans. These Spring Beans are maintained by the IOC which is given to the Client Application upon request. Let us define a data source as follows,

<?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">

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" >
    <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
    <property name="url" value="jdbc:derby://localhost:1527/myeclipse"/>
    <property name="username" value="myblog"/>
    <property name="password" value="myblog"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
        <list>
            <value>/com/Customer.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
              <prop key="hbm2ddl.auto">update</prop>
              <prop key="show_sql">true</prop>
         </props>
    </property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory">
        <ref bean="mySessionFactory"/>
    </property>
</bean>
<bean id="customerDAO" class="com.CustomerDAOImpl">
<property name="hibernateTemplate">
        <ref bean="hibernateTemplate"/>    
    </property>
</bean>
</beans>

1. The above First bean defines a data-source of type 'org.apache.commons.dbcp.BasicDataSource'. More importantly, it defines the various connection properties that are needed for accessing the database. For accessing the Derby database, we need Derby database driver derbyclient.jar
  • The first property called driverClassName should point to the class name of the Derby Database Driver.
  • The second property url represents the URL string which is needed to connect to the Derby Database. 
  • The third and the fourth properties represent the database username and the password needed to open up a database session.
2. Now, let us define the second Spring Bean which is the SessionFactoryBean. If you would have programmed in Hibernate, you will realize that SessionFactoryBean is responsible for creating Session objects through which Transaction and Data accessing is done. Now the same SessionFactoryBean has to be configured in Spring's way as follows,

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
        <list>
            <value>/com/Customer.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
              <prop key="hbm2ddl.auto">update</prop>
              <prop key="show_sql">true</prop>
         </props>
    </property>
</bean>

To make the SessionFactoryBean to get properly configured, we have given two mandatory information. One is the data-source information which contains the details for accessing the database. This we have configured already in the previous step and have referred it here using the 'ref' attribute in the 'property' tag. The second one is a list of Mapping files which contains the mapping information between the database tables and the Java class names. We have defined one such mapping file in section 2 and have referenced the same here with the 'list' tag.

3.The 3rd important Spring Bean is the Hibernate Template. It provides a wrapper for low-level data accessing and manipulation. Precisely, it contains methods for inserting/delting/updating/finding data in the database. For the Hibernate Template to get configured, the only argument is the SessionFactoryBean object as represented in the following section,

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory">
        <ref bean="mySessionFactory"/>
    </property>
</bean>

4.The final Bean definition is the Dao class which is the client facing class. Since this class has to be defined in the Application level, it can contain any number of methods for wrapping data access to the Client. Since we know that it is the Hibernate Template class that interacts with the database, it will be ideal a refer an instance of Hibernate Template to the Dao class

<bean id="customerDAO" class="com.CustomerDAOImpl">
<property name="hibernateTemplate">
        <ref bean="hibernateTemplate"/>    
    </property>
</bean>


CusomerDAOImpl.java

As described earlier, this CustomerDaoImpl class can contain any number of methods that can be accessed by the clients. The design of this class can fall under two choices. One is this class can directly depend on the Hibernate Template object which is injected by the IOC for accessing the data. The second one is that it can make use of the Hibernate API for data accessing. The declaration of the class is as follows,
package com;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

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

public class CustomerDAOImpl extends HibernateDaoSupport {

public Customer findByCustomerId(int custId) {
// TODO Auto-generated method stub
return (Customer)getHibernateTemplate().get(Customer.class, new Integer(custId));
}
public void insert(Customer customer) {
// TODO Auto-generated method stub
getHibernateTemplate().saveOrUpdate(customer);
}
}

Test.java
package com;

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

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context =
     new ClassPathXmlApplicationContext("/applicationContext.xml");
        CustomerDAOImpl customerDAO = (CustomerDAOImpl) context.getBean("customerDAO");
        Customer customer = new Customer(3, "Amith",29);
        customerDAO.insert(customer);
        Customer customer1 = customerDAO.findByCustomerId(2);
        System.out.println(" ::: Customer Record From DataBase ::: ");
        System.out.println(" Customer ID ::: "+customer1.getId());
        System.out.println(" Customer Name ::: "+customer1.getName());
        System.out.println(" Customer Age ::: "+customer1.getAge());
}
}

Finally, we come to the sample client Application for accessing the test data. The control goes like this. When the method BeanFactory.getBean("customerDao") is called, Spring finds the references made in the Bean definition of CustomerDaoImpl Bean. It happens to be the Hibernate Template object. Then an attempt will be made to initialize the Hibernate Template object where it will see that a Session Factory Bean object is referenced. Then, while constructing the Session Factory Bean object, the data-source information will get resolved along with the database tables and the Java classes.


Note *** To run the below example you need below jar files in your class path

  • derbyclient.jar
  • spring-dao.jar
  • spring-jdbc.jar
  • hibernate3.jar
  • jta.jar
  • commons-collections-2.1.1.jar
  • commons-dbcp.jar
  • spring-hibernate3.jar