Himu\’s Attempt at Blogging

Tidbits from my thoughts

Spring MVC Tutorial – Hibernate Integration

with 43 comments

After a long gap…

For introduction to Spring MVC in particular, see Spring MVC Tutorial and Spring MVC Tutorial 2.

The project done in STS can be downloaded from my Box.net account. The project libraries you will have to edit to match your setup.

Along with learning to integrate Hibernate, I’ll be introducing some new pieces of Spring MVC.

For this installment, I am using the following:

  1. JDK 6 update 16
  2. Tomcat 6.0.20
  3. SpringSource Tool Suite 2.2.0 as my IDE
  4. MySQL 5.1
  5. Spring Framework 2.5.6.SEC01 (the bundle with all dependencies included so that I don’t have to look for jars here and there)
  6. JSTL 1.2 (from jstl.dev.java.net)
  7. Hibernate Distribution 3.3.2.GA
  8. Hibernate Annotations 3.4.0.GA
  9. log4j 1.2.15
  10. slf4j 1.5.8
  11. JDBC Driver – MySQL Connector/J 5.1.6

The project is named ‘ibank’ – an Internet portal for bank customers. We’ll be doing customer registration only.

Without any fuss, let’s start.

Setup the Initial Project in STS

  1. Start STS
  2. Create a Dynamic Web Project from File>New>Other
  3. Name the project ‘ibank’
  4. Choose the target runtime – the server on which you’ll be deploying. Create one if already not available.
  5. Keep everything else default (the source, class and web content directories)
  6. After the project is created, right-click on the root node and choose Spring Tools>Add Spring Project Nature

Add the necessary libraries. Following jars will be required:

JAR Source
spring.jar, commons-logging.jar,
commons-dbcp.jar, commons-pool.jar
Spring Framework
jstl-api-1.2.jar, jstl-impl-1.2.jar jstl.dev.java.net
hibernate3.jar, antlr-2.7.6.jar, commons-collections-3.1.jar
dom4j-1.6.1.jar, javassist-3.9.0.GA.jar, jta-1.1.jar
Hibernate Core Distribution
hibernate-annotations.jar, ejb3-persistence.jar
hibernate-commons-annotations.jar
Hibernate Annotations
log4j-1.2.15.jar Log4J
slf4j-api-1.5.8.jar, slf4j-log4j12-1.5.8.jar SLF4J
mysql-connector-java-5.1.6-bin.jar MySQL Connector/J

Happy hunting!

Configure web.xml Spring MVC

Rewrite the auto-generated web.xml with the following (for explanations, see my first Spring MVC Tutorial):

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns=”http://java.sun.com/xml/ns/javaee” xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”
id=”WebApp_ID” version=”2.5″>

<display-name>ibank</display-name>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/ibank-service.xml
/WEB-INF/ibank-persistence.xml
</param-value>
</context-param>

<servlet>
<servlet-name>ibank</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>ibank</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Write the Starting Page

Create a new JSP file in the WebContent folder, STS/Eclipse copies everything from this folder to the root of your web application deployment. To do so,

  1. Right-click WebContent in the project explorer and then New>JSP
  2. Name it index.jsp and accept all defaults
  3. Clean up the generated mess after the @page tag and add just one redirect line:

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<% response.sendRedirect(“home.htm”); %>

Controller and View for home.htm

We need to write a controller for dealing with /index.htm as redirected by index.jsp. After writing the controller, we have to map it in ibank-servlet.xml and also write a JSP that will be used as the returned view.

First, the Controller

The IndexController is a very simple one that records the system date and passes control to DispatcherServlet with the view name ‘home’.

package org.himu.ibank.controller;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

public class HomePageController extends AbstractController {

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {

// time at the server
Date today = Calendar.getInstance().getTime();
ModelAndView mv = new ModelAndView(“home”);
mv.addObject(“today”, today);
return mv;
}
}

Creating the Spring Bean Definition Files

Before we configure the beans in Spring we create all three bean configuration files and tell the IDE to treat them under a single set.

  1. In Project Explorer, right-click Java Resources: src and then click New>Other, select Spring Bean Configuration File
  2. When prompted, choose the WebContent>WEB-INF folder, give the exact name ‘ibank-servlet.xml’ (ibank is the DispatcherServlet’s name in web.xml) and click Next
  3. In the next dialog, beans namespace is pre-selected – click on it and be sure to check the 2.5 version of the XSD, click Finish
  4. Create ibank-service.xml and ibank-persistence.xml in a similar fashion
  5. In Project Explorer, expand Spring Elements, right-click Beans and choose Properties. The three files created should be shown in the Config Files tab
  6. Go to Config Sets tab and click the New button
  7. Give a name of your choice (I chose ibank-beans), click Select All and then OK
  8. Close the Properties dialog

Mapping the Controller and View

Now we make the Spring MVC related configurations in ibank-servlet.xml. First we setup the controller mapping using SimpleUrlHandlerMapping (which will be used for other controllers as well) and the setup the view resolver InternalResourceViewResolver which takes any view name and generates the corresponding JSP page name.

<?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.5.xsd”>

<bean id=”simpleUrlMapping” class=”org.springframework.web.servlet.handler.SimpleUrlHandlerMapping”>
<property name=”mappings”>
<props>
<prop key=”/home.htm”>homePageController</prop>
</props>
</property>
</bean>

<bean id=”viewResolver” class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”prefix” value=”/WEB-INF/jsp/”/>
<property name=”suffix” value=”.jsp”/>
</bean>

<bean id=”homePageController” class=”org.himu.ibank.controller.HomePageController”/>

</beans>

Writing the View JSP

We’ll write all your JSP’s under WEB-INF/jsp folder as indicated in the view resolver above. So, create a new folder names jsp under WEB-INF and then create a new JSP file names home.jsp:

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<!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=UTF-8″>
<title>iBank – Home</title>
</head>
<body>
<h1 align=”center”>Welcome to iBank</h1>
<h2 align=”center”>Your Online Bank Portal</h2>
<p align=”center”>
Today is ${today}.<br/>
<a href=”<%=request.getContextPath()%>/adminhome.htm”>Administration Site</a>
</p>
</body>
</html>

Test Running the Application

If a Tomcat runtime is not configured with the IDE then

  1. Go to Window>Preferences, expand Server node in the tree on the left and select Runtime Environments
  2. Click Add and choose your Tomcat version (shouldn’t be less than 5.5), click Next
  3. If the IDE doesn’t auto-detect your CATALINA_HOME (or you haven’t defined any) then Browse and point to the installation folder, click Finish
  4. Go to Window>Show View>Servers
  5. Right-click on the Servers panel and choose New>Server
  6. Select the server type and check if the server runtime environment shows the one created in steps 1-3
  7. Click Next
  8. At this point, the IDE will give you an option to make your project available to the created server
  9. Select your application and click Add, then click Finish

If your controller shows errors with the HttpServlet… classes

  1. Right-click your project root, select Build Path>Configure Build Path
  2. Select the Libraries tab
  3. Click Add Library, then choose Server Runtime and select your Tomcat server

If Tomcat is already configured in your IDE then

  1. Open the Servers panel (Window>Show View>Servers)
  2. Right-click your server and choose Add and Remove
  3. Add your application and click Finish

Finally, to run your application, right-click on the server and click Publish. Then start the server by right-click and Start.

Fire up your browser and point to http://localhost:8080/ibank.

Setting Up the Admin Site

I’ll be doing some fun stuff here to make the site look a bit better. Some CSS techniques are applied (not my invention).

  1. Under WEB-INF/jsp, create a new folder named admin
  2. Create three JSP files: admin.jsp, menu.jsp, and footer.jsp
  3. Under WebContent folder, create a new CSS file names master.css
  4. Edit the files so that they look similar to the following

master.css

@CHARSET “UTF-8”;

html, body {
margin: 0; padding: 0; height: 100%; background: #FFFFFF;
}

#mask {
position: relative; min-height: 100%; margin-bottom: -25px;
}

#header {
background: #006699; width: 100%; height: 100px; overflow: hidden;
}

#content-wrapper {
float: left; width: 100%; background: #DDEEFF; overflow: hidden;
position: relative; min-height: 100%;
border-color: black; border-style: solid; border-width: thin;
}

#leftcol-wrapper {
float: left; width: 100%; background: #6699CC;
position: relative; right: 80%; min-height: 100%;
border-color: black; border-style: solid; border-width: thin;
}

#leftcol {
float: left; width: 18%; position: relative;
left: 81%; padding-bottom: 25px;
}

#content {
float: left; width: 78%; position: relative;
left: 83%; padding-bottom: 25px; overflow: hidden;
}

#footer {
background: #444444; color: #FFFFFF; position: relative;
overflow: hidden; width: 100%; bottom: 0; height: 25px;
}

#clearfooter {
height: 25px; clear: both;
}

menu.jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<ul>
<li><a href=”<%=request.getContextPath()%>/adminhome.htm”>Admin Home</a></li>
<li><a href=”<%=request.getContextPath()%>/createcust.htm”>Create New Customer</a></li>
<li><a href=”<%=request.getContextPath()%>/viewcustlist.htm”>Customer List</a></li>
</ul>

footer.jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
&copy; 2009 Himu

admin.jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<!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=UTF-8″>
<title>iBank – Administration</title>
<link rel=”stylesheet” href=”css/master.css” type=”text/css” />
</head>
<body>
<div id=”mask”>
<div id=”header”>
<h1>iBank – Administration</h1>
</div>
<div id=”content-wrapper”>
<div id=”leftcol-wrapper”>
<div id=”leftcol”><jsp:include page=”menu.jsp”/></div>
<div id=”content”>
</div>
</div>
</div>
<div id=clearfooter”></div>
</div>
<div id=”footer” align=”center”>
<jsp:include page=”footer.jsp”/>
</div>
</body>
</html>

Configuring Spring MVC

After the .jsp and .css files are in place, add the following mapping in ibank-servlet.xml under simpleUrlMapping bean (The /adminhome.htm is referred to in home.jsp):

<prop key=”/adminhome.htm”>adminHomePageController</prop>

We won’t be writing the adminHomePageController implementation. Instead, we’ll be using one of Spring MVC’s built-in controller as there is no processing involved from our part. Add this in ibank-servlet.xml:

<bean id=”adminHomePageController” class=”org.springframework.web.servlet.mvc.ParameterizableViewController”>
<property name=”viewName” value=”admin/admin”/>
</bean>

The admin/admin view name get mapped to /WEB-INF/jsp/admin/admin.jsp by the view resolver.

Go, test the new admin page.

Hibernate – Configuration Basics

This is not a tutorial about Hibernate. So don’t expect even a decent introduction!

The starting point of a Hibernate setup is the SessionFactory. SessionFactory can be configured using an XML file or using Annotations or even raw programmatic manipulation. For the traditional XML configuration using .hbm.xml mapping documents, you instantiate it using the following code:

SessionFactory sf = new Configuration().configure().buildSessionFactory();

For the annotation-supported SessionFactory (supports both EJB3 and Hibernate-specific annotation), use the following:

SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();

In both cases, hibernate.cfg.xml – the core hibernate configuration file – must be available in the classpath.

A typical hibernate.cfg.xml file for using mapping documents is as follows (adapted from Hibernate docs):

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

<!– Database connection settings –>
<property name=”connection.driver_class”>org.hsqldb.jdbcDriver</property>
<property name=”connection.url”>jdbc:hsqldb:hsql://localhost</property>
<property name=”connection.username”>sa</property>
<property name=”connection.password”></property>

<!– SQL dialect –>
<property name=”dialect”>org.hibernate.dialect.HSQLDialect</property>

<!– Enable Hibernate’s automatic session context management –>
<property name=”current_session_context_class”>thread</property>

<mapping resource=”org/hibernate/tutorial/domain/Event.hbm.xml”/>

</session-factory>

</hibernate-configuration>

A annotation-based configuration is similar to the following (from Hibernate docs):

<?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”&gt;

<hibernate-configuration>
<session-factory>
<mapping package=”test.animals”/>
<mapping class=”test.Flight”/>
<mapping class=”test.Sky”/>
<mapping class=”test.Person”/>
<mapping class=”test.animals.Dog”/>
<mapping resource=”test/animals/orm.xml”/>
</session-factory>
</hibernate-configuration>

Now let’s look at a typical use of Hibernate API (again from Hibernate docs):

private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();

Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);

session.getTransaction().commit();
}

With Spring in control, we’ll be eliminating a lot of this!

Hibernate in Spring

The configuration information will be places in ibank-persistence.xml just to separate the persistence-related information. Here is the basic outline:

  1. Take out the database connection information out of Hibernate and manage it through Spring.
  2. Configure Hibernate SessionFactory using Spring’s built-in support, eliminating the need for a hibernate.cfg.xml.

Edit ibank-persistence.xml so that it looks like the following:

<?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.5.xsd”>

<bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource”>
<property name=”driverClassName” value=”com.mysql.jdbc.Driver”/>
<property name=”url” value=”jdbc:mysql://localhost/ibankdb”/>
<property name=”username” value=”ibankusr”/>
<property name=”password” value=”pass123″/>
<!– connection pooling details –>
<property name=”initialSize” value=”1″/>
<property name=”maxActive” value=”5″/>
</bean>
<bean id=”sessionFactory”
class=”org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”>
<property name=”dataSource” ref=”dataSource”/>
<property name=”hibernateProperties”>
<props>4
<prop key=”hibernate.dialect”>org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key=”hibernate.show_sql”>true</prop>
<prop key=”hibernate.hbm2ddl.auto”>update</prop>
</props>
</property>
<property name=”annotatedClasses”>
<list>
<!– all the annotation entity classes –>
</list>
</property>
</bean>
</beans>

The dataSource bean defines a DBCP connection pool with the necessary info to connect to a MySQL database named ibankdb on the localhost. The sessionFactory bean is our Hibernate SessionFactory configured entirely through Spring. Note that the annotatedClasses list is empty as we haven’t defined any entity classes to be persisted. We’ll add to it in due time.

Defining the Persistence and DAO (Data Access Object) Classes

We want to register new customers and then approve them in our system. Create a Customer class under org.himu.ibank.domain:

package org.himu.ibank.domain;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Customer {

public static int STATUS_REGISTERED = 0;
public static int STATUS_ACTIVE = 1;
public static int STATUS_INACTIVE = 2;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name=”CUST_ID”)
private Long id;

@Column(name=”USER_ID”, unique=true)
private String userId;
@Column(name=”USER_PWD”)
private String password;
@Column
private String firstName;
@Column
private String lastName;
@Column
private String email;
@Column
private int status;

public Customer() {
id = null;
status = STATUS_REGISTERED;
}

// getters and setters

}

This is not a Hibernate tutorial. But still some discussion. We must tell Hibernate that we want a class/POJO to be treated as persistent – using the @Entity annotation. Each field to be mapped to the database needs to be marked with the @Column annotation except the primary key which is annotated with @Id. The additional @Column annotation for the id field is used to explicitly map it to a column name of our choice (CUST_ID). The unique attribute for userId is set to true so that a unique index for it is used. The @GeneratedValue annotation tells the persistence provider to choose the best primary key generation technique for the underlying database – an auto-increment integer for MySQL.

Instead of creating a DAO class directly, we use an interface for segregation of specification and implementation. This way we will be able to change the implemenation to JPA or some other ORM in the future – without affecting our client code. Following is the interface CustomerDao:

package org.himu.ibank.dao;

import java.util.List;

import org.himu.ibank.domain.Customer;

public interface CustomerDao {

Long addNew(Customer c);
void delete(Customer c);
void update(Customer c);
Customer findById(Long id);
Customer findByUserId(String uid);
List<Customer> listAll();
List<Customer> listAll(int startPage, int pageSize);
List<Customer> listByExample(Customer c);
List<Customer> listByExample(Customer c, int startPage, int pageSize);
}

Following is the implementation class, HibernateCustomerDao:

package org.himu.ibank.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.himu.ibank.domain.Customer;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibernateCustomerDao extends HibernateDaoSupport implements
CustomerDao {

@Override
public Long addNew(Customer c) {
return (Long) getHibernateTemplate().save(c);
}

@Override
public void delete(Customer c) {
getHibernateTemplate().delete(c);
}

@Override
public void update(Customer c) {
getHibernateTemplate().update(c);
}

@Override
public Customer findById(Long id) {
return (Customer) getHibernateTemplate().get(Customer.class, id);
}

@SuppressWarnings(“unchecked”)
@Override
public Customer findByUserId(String uid) {
List<Customer> clist =  getHibernateTemplate().find(“from Customer c where c.userId = ?”, uid);
if (clist.isEmpty())
return null;
else
return clist.get(0);
}

@SuppressWarnings(“unchecked”)
@Override
public List<Customer> listAll() {
return getHibernateTemplate().find(“from Customer c”);
}

@SuppressWarnings(“unchecked”)
@Override
public List<Customer> listAll(int startPage, int pageSize) {
DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
criteria.addOrder(Order.asc(“id”));
return getHibernateTemplate().findByCriteria(criteria, startPage, pageSize);
}

@SuppressWarnings(“unchecked”)
@Override
public List<Customer> listByExample(Customer c) {
return getHibernateTemplate().findByExample(c);
}

@SuppressWarnings(“unchecked”)
@Override
public List<Customer> listByExample(Customer c, int startPage, int pageSize) {
return getHibernateTemplate().findByExample(c, startPage, startPage);
}

}

The beauty of using Spring springs to life is this case. We’re extending our DAO from HibernateDaoSupport which encapsulates all the gory details of dealing with Hibernate directly. The magic comes through the use of a HibernateTemplate which we get a reference to using getHibernateTemplate(). As you can see, HibernateTemplate gives us convenient methods to do all the common things of Hibernate. Still we need to do some specifics:

  • findByUserId() uses an HQL (Hibernate Query Language) statement to filter results by userId and not the primary key (id in this case).
  • listAll() method uses the simplest select all statement.
  • listAll(startPage, pageSize) uses DetachedCriteria (a Spring gift) for paging support.
  • listByExample(…) methods use Hibernates query-by-example (QBE) facility.

Once the classes are ready, we configure them in Spring in ibank-persistence.xml. The data source and session factory are already there. We add our domain class Customer to the list of annotated classes. And we configure our DAO as well.

<bean id=”sessionFactory”

<property name=”annotatedClasses”>
<list>
<value>org.himu.ibank.domain.Customer</value>
</list>
</property>
</bean>
<bean id=”customerDao”
class=”org.himu.ibank.dao.HibernateCustomerDao”>
<property name=”sessionFactory” ref=”sessionFactory”/>
</bean>
</beans>

Defining the Service Classes

It’s no use writing the domain and DAO classes only. We need a service class for interacting with the UI as well. As usual we separate the interface and implementation. First, the interface:

package org.himu.ibank.service;

import java.util.List;

import org.himu.ibank.domain.Customer;

public interface CustomerRegistrationService {

Long registerCustomer(Customer c);
void authorizeCustomer(Customer c);
List<Customer> getUnauthorizedCustomers(int startPage, int pageSize);
List<Customer> getCustomers(int startPage, int pageSize);
List<Customer> getAllCustomers(int startPage, int pageSize);
}

Then, we write the actual implementation:

package org.himu.ibank.service;

import java.util.List;

import org.himu.ibank.dao.CustomerDao;
import org.himu.ibank.domain.Customer;

public class StandardCustomerRegistrationService implements
CustomerRegistrationService {

private CustomerDao custDao;
public void setCustDao(CustomerDao custDao) {
this.custDao = custDao;
}

@Override
public Long registerCustomer(Customer c) {
return custDao.addNew(c);
}

@Override
public void authorizeCustomer(Customer c) {
if (c.getStatus() == Customer.STATUS_REGISTERED) {
c.setStatus(Customer.STATUS_ACTIVE);
custDao.update(c);
// … mailer code for notifying customer …
}
}

/**
* Get registered but unauthorized customers using optional paging.
*
* @param startPage Starting page number, first page is 0
* @param pageSize Size of a single page, <=0 means no paging
*/
@Override
public List<Customer> getUnauthorizedCustomers(int startPage, int pageSize) {
Customer c = new Customer();
c.setStatus(Customer.STATUS_REGISTERED);
return custDao.listByExample(c, startPage, pageSize);
}

/**
* Get registered and authorized customers using optional paging.
*
* @param startPage Starting page number, first page is 0
* @param pageSize Size of a single page, <=0 means no paging
*/
@Override
public List<Customer> getCustomers(int startPage, int pageSize) {
Customer c = new Customer();
c.setStatus(Customer.STATUS_ACTIVE);
return custDao.listByExample(c, startPage, pageSize);
}

@Override
public List<Customer> getAllCustomers(int startPage, int pageSize) {
return custDao.listAll(startPage, pageSize);
}
}

Now we need to tell Spring about our service class in ibank-service.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.5.xsd”>

<bean id=”customerRegService”
class=”org.himu.ibank.service.StandardCustomerRegistrationService”>
<property name=”custDao” ref=”customerDao”/>
</bean>
</beans>

New Customer Registration

We have our domain, DAO, and service classes written and configured in Spring. Now we’ll write our Spring MVC things for registering a new customer. Here’s the outline:

  1. User clicks on new customer registration link
  2. System presents new customer input page
  3. User fills in the details and submits
  4. System verifies data – omitted from this tutorial
  5. System saves the new customer and displays summary

We will first write the controller.

NewCustomerController.java

package org.himu.ibank.controller;

import java.util.HashMap;
import java.util.Map;

import org.himu.ibank.domain.Customer;
import org.himu.ibank.service.CustomerRegistrationService;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class NewCustomerController extends SimpleFormController {

private CustomerRegistrationService custRegService;

public void setCustRegService(CustomerRegistrationService custRegService) {
this.custRegService = custRegService;
}

@Override
protected ModelAndView onSubmit(Object command) throws Exception {
Customer c = (Customer) command;
custRegService.registerCustomer(c);
Map<Object, Object> map = new HashMap<Object, Object>();
map.put(getCommandName(), c);
return new ModelAndView(getSuccessView(), map);
}
}

We could have overridden doSubmitAction() for in NewCustomerController but I just wanted to show you how to use the model and view names provided in the configuraiton file (shown later).

admin/newcustomer.jsp

Customer registration is an administration thing. We’ve already defined a nice looking (!) template in admin.jsp which we want to re-use. If we had used Tiles then that would have been taken care of. But we’re not using Tiles. So, for now, lets make a copy of the admin.jsp in STS by selecting it in the Project Explorer, then pressing Ctrl+C and Ctrl+V in sequence. STS understands and prompts you to provide a name for the new copy. Name it newcustomer.jsp and modify the contents of the ‘mask’ div as follows:

<div id=”mask”>
<div id=”header”>
<h1>iBank – Register New Customer</h1>
</div>
<div id=”content-wrapper”>
<div id=”leftcol-wrapper”>
<div id=”leftcol”><jsp:include page=”menu.jsp”/></div>
<div id=”content”>
<form:form method=”post” commandName=”customer”>
<form:errors path=”*”/>
<!– userid, password, fname, lname, email, status –>
<table>
<tr><td>User ID</td><td><form:input path=”userId”/></td></tr>
<tr><td>Password</td><td><form:password path=”password”/></td></tr>
<tr><td>First Name</td><td><form:input path=”firstName”/></td></tr>
<tr><td>Last Name</td><td><form:input path=”lastName”/></td></tr>
<tr><td>E-mail</td><td><form:input path=”email”/></td></tr>
<tr><td>&nbsp;</td><td><input type=”submit”/></td></tr>
</table>
</form:form>
</div>
</div>
</div>
<div id=clearfooter”></div>
</div>

admin/newcustomer-success.jsp

Create the success view JSP by copying admin.jsp and modifying as follows:

<div id=”mask”>
<div id=”header”>
<h1>iBank – New Customer ${customer.userId} Registered Successfully</h1>;
</div>
<div id=”content-wrapper”>
<div id=”leftcol-wrapper”>
<div id=”leftcol”><jsp:include page=”menu.jsp”/></div>
<div id=”content”>
<table>
<tr><td>System ID</td><td>${customer.id}</td></tr>
<tr><td>User ID</td><td>${customer.userId}</td></tr>
<tr><td>Password</td><td><i>secret</i></td></tr>
<tr><td>First Name</td><td>${customer.firstName}</td></tr>
<tr><td>Last Name</td><td>${customer.lastName}</td></tr>
<tr><td>E-mail</td><td>${customer.email}</td></tr>
</table>
<a href=”<%=request.getContextPath()%>/createcust.htm”>Register Another Customer</a>
</div>
</div>
</div>
<div id=clearfooter”></div>
</div>

Binding the Controller and Views

Now that we have our files ready, we can configure them in ibank-servlet.xml. Following is the bean entry for NewCustomerController:

<bean id=”newCustomerController” class=”org.himu.ibank.controller.NewCustomerController”>
<property name=”custRegService” ref=”customerRegService”/>
<property name=”formView” value=”admin/newcustomer”/>
<property name=”successView” value=”admin/newcustomer-success”/>
<property name=”commandName” value=”customer”/>
<property name=”commandClass” value=”org.himu.ibank.domain.Customer”/>
</bean>

We also must not forget the url mapping under simpleUrlMapping:

<prop key=”/createcust.htm”>newCustomerController</prop>

The Project Structure

We’re done for our first Hibernate test. Following is a snapshot of the STS project structure:

Spring MVC - Hibernate STS Project

That’s It!

I feel this entry is quite long. But I couldn’t help but detail all the steps that I’ve gone through so that anyone can recreate the whole thing from scratch.

I’ll be expanding the project to contain a Customer browsing and authorization part. Another blog entry for that. Hope this was useful to you. Comments welcome!

Advertisements

Written by mhimu

November 16, 2009 at 2:44 pm

Posted in Java, spring

Tagged with , , ,

43 Responses

Subscribe to comments with RSS.

  1. Sorry guys! There is a mistake in HibernateCustomerDao above (as well as in the source code download).

    Instead of

    listByExample(startPage, pageSize)
    or
    listByExample(startPage, startPage)

    the code should be

    listByExample(startPage * pageSize, pageSize)

    mhimu

    November 24, 2009 at 11:17 am

    • Hi
      Before changing the above, the application is running fine. but when i need to find customer list, then i got the following error.

      675796 [http-9999-2] WARN servlet.PageNotFound – No mapping for [/ibank/viewcustlist.htm] in DispatcherServlet with name ‘ibank’

      Regards
      Sanjay

      sanjay

      March 11, 2011 at 6:40 pm

  2. […] a comment » In this installment, I’m expanding the project done in Spring MVC Tutorial – Hibernate Integration to […]

  3. […] Spring MVC Tutorial – Hibernate Integration – build a Spring MVC app using Hibernate from the ground up. […]

  4. Himu,

    This is the great article and helped me a lot in inderstanding Spring related concepts in my first Spring based project.

    By the way when are you going to have article on “Customer browsing and authorization part”. Please publish it as early as possible. I am very excited to see that.

    Thanks,
    Satish

    Satish

    December 30, 2009 at 9:56 am

  5. could you please add script needed to create the needed tables in database

    ravikumar

    July 22, 2010 at 7:52 pm

    • hello ravi,

      you don’t need a separate script for the db. it is automatically created by Hibernate. The trick is in

      <prop key=”hibernate.hbm2ddl.auto”>update</prop>

      mhimu

      July 25, 2010 at 4:27 pm

  6. how can we view customer list

    manoj

    August 2, 2010 at 3:32 pm

  7. Thanks for the tutorial, your tutorial really help me (newbie) understand more about spring/hibernate. One question though; How do I put the hibernate and the persistence to connect to the oracle db?

    wdzul

    August 12, 2010 at 10:31 pm

    • First of all you need the appropriate oracle JDBC driver library (e.g. ojdbc14.jar).
      After that, in ibank-persistence.xml, change the dataSource bean definition to use the Oracle driver (oracle.jdbc.OracleDriver) and corresponding URL (jdbc:oracle:thin:@<server>:<port>:<sid>).
      Next, change the Hibernate dialect to org.hibernate.dialect.Oracle10gDialect (or whatever appropriate).

      The same goes for any database.

      mhimu

      August 17, 2010 at 11:10 am

  8. HI Himu,
    Its very nice tutorial,able to create spring webapplication very easily…
    Thank you

    Leela

    November 12, 2010 at 12:46 pm

  9. hey guys. i have one problem.

    Error creating bean with name ‘dataSource’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/KeyedObjectPoolFactory

    could u show ur database? and

    mglsodo

    November 26, 2010 at 11:57 pm

  10. It a nice simple tutorial for hibernate with Spring MVS

    Santhosh

    January 12, 2011 at 6:54 pm

  11. Descriptive tutorial….. If you can post a tutorial utilizing the spring annotation support…

    Aneer Indian

    February 11, 2011 at 12:42 pm

  12. hi Himu,
    Its a simple and very nice tutorial.
    But I get the following exception when i run it… kindly help to sort this out..

    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerRegService’ defined in ServletContext resource [/WEB-INF/ibank-service.xml]: Cannot resolve reference to bean ‘customerDao’ while setting bean property ‘customerDao’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerDao’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Cannot resolve reference to bean ‘sessionFactory’ while setting bean property ‘sessionFactory’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/MappingException

    lakmal

    June 9, 2011 at 10:15 am

    • hi guys for tomcat 5.5 in eclipse
      1.download and paste the following jars in (WEB-INF/lib) folder
      (antlr-2.7.5, antlr-runtime-3.0, asm, cglib-2.2, commons-collections-3.1, commons-dbcp, commons-logging-1.1.1, commons-pool, dom4j-1.6.1, ejb3-persistence, hibernate3, hibernate-annotations, hibernate-commons-annotations, javassist-3.4.ga, javaee, javax.el, jstl-1.1.0, jstl-1.2, jta-1.1, log4j, mysql-connector-java-5.1.15, servlet-api, slf4j-api-1.5.6, slf4j-log4j12-1.5.10, spring, standard)

      2.in web.xml change version to 2.4(replace 2.5 in dtd with 2.4).
      3. in in 3 other xmls (servlet, service, etc)replace javaee to j2ee in dtd.
      4.in the above 3 xmls replace “spring-beans-2.5.xsd” in DTD to “spring-beans.xsd “.

      run tomcat and i think every thing should be working
      good luck
      regards,
      Sachin.S

      Sachin.S

      June 22, 2011 at 3:46 pm

      Sachin.S

      June 23, 2011 at 3:23 pm

  13. hi guys for tomcat 5.5 in eclipse
    1.download and paste the following jars in (WEB-INF/lib) folder
    (antlr-2.7.5, antlr-runtime-3.0, asm, cglib-2.2, commons-collections-3.1, commons-dbcp, commons-logging-1.1.1, commons-pool, dom4j-1.6.1, ejb3-persistence, hibernate3, hibernate-annotations, hibernate-commons-annotations, javassist-3.4.ga, javaee, javax.el, jstl-1.1.0, jstl-1.2, jta-1.1, log4j, mysql-connector-java-5.1.15, servlet-api, slf4j-api-1.5.6, slf4j-log4j12-1.5.10, spring, standard)

    2.in web.xml change version to 2.4(replace 2.5 in dtd with 2.4).
    3. in in 3 other xmls (servlet, service, etc)replace javaee to j2ee in dtd.
    4.in the above 3 xmls replace “spring-beans-2.5.xsd” in DTD to “spring-beans.xsd “.

    run tomcat and i think every thing should be working
    good luck
    regards,
    Sachin.S

    Sachin.S

    Sachin.S

    June 23, 2011 at 3:22 pm

  14. Hi,
    I am facing below mentioned error. i kept project name is rbank instead of ibank.

    SEVERE: StandardWrapper.Throwable
    java.lang.IllegalStateException: Context attribute is not of type WebApplicationContext: org.springframework.web.context.support.XmlWebApplicationContext@16c79d7: display name [Root WebApplicationContext]; startup date [Tue Aug 23 19:21:28 IST 2011]; root of context hierarchy
    at org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(WebApplicationContextUtils.java:113)
    at org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(WebApplicationContextUtils.java:86)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:291)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:262)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126)
    at javax.servlet.GenericServlet.init(GenericServlet.java:241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4420)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4733)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Aug 23, 2011 7:21:30 PM org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /rbank threw load() exception
    java.lang.IllegalStateException: Context attribute is not of type WebApplicationContext: org.springframework.web.context.support.XmlWebApplicationContext@16c79d7: display name [Root WebApplicationContext]; startup date [Tue Aug 23 19:21:28 IST 2011]; root of context hierarchy
    at org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(WebApplicationContextUtils.java:113)
    at org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(WebApplicationContextUtils.java:86)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:291)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:262)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126)
    at javax.servlet.GenericServlet.init(GenericServlet.java:241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4420)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4733)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Aug 23, 2011 7:21:30 PM org.apache.coyote.http11.Http11AprProtocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    Aug 23, 2011 7:21:30 PM org.apache.coyote.ajp.AjpAprProtocol start
    INFO: Starting Coyote AJP/1.3 on ajp-8009
    Aug 23, 2011 7:21:30 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 2969 ms

    Rajib Pal

    August 23, 2011 at 7:54 pm

  15. Hi,

    I face the following error when export WAR file from Eclipse and deploy in Tomcat 7.

    name of war is iBank

    Database Information:
    iBank
    MySql

    Table Information:

    CREATE TABLE IF NOT EXISTS `customer` (
    `CUST_ID` int(11) NOT NULL AUTO_INCREMENT,
    `USER_ID` varchar(45) NOT NULL,
    `USER_PWD` varchar(45) NOT NULL,
    `firstName` varchar(45) NOT NULL,
    `lastName` varchar(45) NOT NULL,
    `email` varchar(45) NOT NULL,
    `status` int(5) NOT NULL,
    PRIMARY KEY (`CUST_ID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

    Aug 29, 2011 1:34:22 AM org.apache.catalina.startup.HostConfig deployWAR
    INFO: Deploying web application archive iBank_V1.3.war
    Aug 29, 2011 1:34:26 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
    INFO: validateJarFile(C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\iBank_V1.3\WEB-INF\lib\javaee.jar) – jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
    Aug 29, 2011 1:34:26 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
    INFO: validateJarFile(C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\iBank_V1.3\WEB-INF\lib\servlet-api-2.4.jar) – jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://java.sun.com/jstl/core_rt is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://java.sun.com/jstl/core is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://java.sun.com/jstl/fmt_rt is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://java.sun.com/jstl/fmt is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://jakarta.apache.org/taglibs/standard/permittedTaglibs is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://jakarta.apache.org/taglibs/standard/scriptfree is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://java.sun.com/jstl/sql_rt is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://java.sun.com/jstl/sql is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://java.sun.com/jstl/xml_rt is already defined
    Aug 29, 2011 1:34:27 AM org.apache.catalina.startup.TaglibUriRule body
    INFO: TLD skipped. URI: http://java.sun.com/jstl/xml is already defined
    Aug 29, 2011 1:34:27 AM org.springframework.web.context.ContextLoader initWebApplicationContext
    INFO: Root WebApplicationContext: initialization started
    Aug 29, 2011 1:34:27 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing Root WebApplicationContext: startup date [Mon Aug 29 01:34:27 IST 2011]; root of context hierarchy
    Aug 29, 2011 1:34:27 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/ibank-service.xml]
    Aug 29, 2011 1:34:27 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/ibank-persistence.xml]
    Aug 29, 2011 1:34:27 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1ba614a: defining beans [customerRegService,dataSource,sessionFactory,customerDao]; root of factory hierarchy
    Aug 29, 2011 1:34:27 AM org.hibernate.cfg.annotations.Version
    INFO: Hibernate Annotations 3.2.0.GA
    Aug 29, 2011 1:34:28 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
    INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1ba614a: defining beans [customerRegService,dataSource,sessionFactory,customerDao]; root of factory hierarchy
    Aug 29, 2011 1:34:28 AM org.springframework.web.context.ContextLoader initWebApplicationContext
    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerRegService’ defined in ServletContext resource [/WEB-INF/ibank-service.xml]: Cannot resolve reference to bean ‘customerDao’ while setting bean property ‘custDao’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerDao’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Cannot resolve reference to bean ‘sessionFactory’ while setting bean property ‘sessionFactory’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: class org.hibernate.cfg.ExtendedMappings has interface org.hibernate.cfg.Mappings as super class
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1317)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1076)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerDao’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Cannot resolve reference to bean ‘sessionFactory’ while setting bean property ‘sessionFactory’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: class org.hibernate.cfg.ExtendedMappings has interface org.hibernate.cfg.Mappings as super class
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1317)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1076)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    … 23 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: class org.hibernate.cfg.ExtendedMappings has interface org.hibernate.cfg.Mappings as super class
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    … 33 more
    Caused by: java.lang.IncompatibleClassChangeError: class org.hibernate.cfg.ExtendedMappings has interface org.hibernate.cfg.Mappings as super class
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2818)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1148)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1643)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.hibernate.cfg.AnnotationConfiguration.createExtendedMappings(AnnotationConfiguration.java:166)
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:254)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1206)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409)
    … 40 more
    Aug 29, 2011 1:34:28 AM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error listenerStart
    Aug 29, 2011 1:34:28 AM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Context [/iBank_V1.3] startup failed due to previous errors

    ashwinparmar

    August 29, 2011 at 2:09 am

  16. hai ,i tried to execute this in eclipse helieos with Tomcat 6…i got an error as folows

    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/ibank-persistence.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: class org.hibernate.cfg.ExtendedMappings has interface org.hibernate.cfg.Mappings as super class

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Caused by: java.lang.IncompatibleClassChangeError: class org.hibernate.cfg.ExtendedMappings has interface org.hibernate.cfg.Mappings as super class
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2818)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1159)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.hibernate.cfg.AnnotationConfiguration.createExtendedMappings(AnnotationConfiguration.java:166)
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:254)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1206)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409)
    … 27 more
    Jan 30, 2012 9:56:31 AM org.apache.catalina.core.StandardContext start
    SEVERE: Error listenerStart
    Jan 30, 2012 9:56:31 AM org.apache.catalina.core.StandardContext start
    SEVERE: Context [/HibernatePagination] startup failed due to previous errors
    Jan 30, 2012 9:56:31 AM org.apache.catalina.core.ApplicationContext log
    INFO: Closing Spring root WebApplicationContext
    Jan 30, 2012 9:56:32 AM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    Jan 30, 2012 9:56:32 AM org.apache.jk.common.ChannelSocket init
    INFO: JK: ajp13 listening on /0.0.0.0:8009
    Jan 30, 2012 9:56:32 AM org.apache.jk.server.JkMain start
    INFO: Jk running ID=0 time=0/32 config=null
    Jan 30, 2012 9:56:32 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 1857 ms

    Dhanapathi

    January 30, 2012 at 10:43 am

  17. Hi,
    Thanks lot for this tutorial, everything is working fine, please you said you will epend this application, can you tell me if you did it and where can I see it.
    thanks lot.

    Kamal

    March 19, 2012 at 10:01 am

    • Sorry, I’ve been so much busy with diversified tasks. I’ve recently taken up a project in Spring 3.1 MVC and hope to share my experiences.

      mhimu

      May 22, 2012 at 1:26 pm

      • hi mhimu….

        very much thanks for the posts. can u please provide us the ibank application with ajax tiles..i am trying but no luck…

        bdmkteam

        July 27, 2012 at 8:56 pm

  18. In this part the showCustomer doesn’t work .. i just give resource not found error on localhost …

    thought the next part does solve this .. but nah .. doesn’t work as intended

    rube

    March 20, 2012 at 5:41 pm

  19. i am new to all the jsp, spring thing .. so i don’t have any clew what might be wrong 😦

    rube

    March 20, 2012 at 5:43 pm

  20. Aw, this was an extremely nice post. Taking the time and actual effort to generate a
    superb article… but what can I say… I hesitate a whole lot and don’t manage to get nearly anything done.

    end of time 2012

    December 31, 2012 at 2:21 pm

  21. Hi! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche.

    Your blog provided us beneficial information to work on.
    You have done a marvellous job!

    Valentina

    April 8, 2013 at 12:40 pm

  22. Hello to every one, the contents existing at this web site are genuinely awesome for people knowledge, well, keep up
    the good work fellows.

    xxxhardcoretubes.com

    May 29, 2013 at 10:47 pm

  23. You really make it seem so easy with your presentation but I find this topic to be actually something that I
    think I would never understand. It seems too complex and extremely
    broad for me. I am looking forward for your next post, I’ll try to get the hang of it!

    forex trading

    July 2, 2013 at 4:45 pm

  24. I’m not that much of a online reader to be honest but your sites really
    nice, keep it up! I’ll go ahead and bookmark your website to come back later. Cheers

    skirted bikini

    July 20, 2013 at 1:32 am

  25. In this example, you’ll need to look for your company that has probably the most
    reasonable fees. Common routes are often traveled destinations by shipping companies usually major cities and ports.
    Suppose a national average cost per gallon of gas of $3.

  26. We must now be responsible and courageous, however, investigating to
    see the actual truth of this body we hold so dear.

    This unique type of investigation, this stirring of the mud,is
    called mindfulness, and is most effectively accomplished
    immediately after coming out of ‘fixed concentration,’ which is that full,
    bright calm that is experienced when our meditation object
    disappears and after the visions and voices of
    ‘threshold concentration’ cease. That means that although there is
    another world, it will be so entirely different
    that we cannot ever speak of it.

  27. Suddenly, there is a bright light, and your
    soul somehow flies higher than the universe itself, higher than you could ever
    even conceive of it flying. t und Vergleichbarkeit impliziert,
    dass, wenn wir ein Material Fehler zu finden in unserem
    Ranking, wir alle schnell auswerten und das Problem angehen transparent”, behauptet Ed Sweeney, der Sprecher S & P. Vail seems to offer it all from spas, shopping, skiing, and even nightlife.

  28. Choose some of them for calling and asking them about your preferences or
    you are able to request an estimate. If people are
    within the car together with you, they are going to feel the
    tension within the air and you’ll all wish you shipped the car instead.
    You fill out a single form and get car shipping quotes emailed directly for your inbox.

  29. American Auto Shipping now has produced it possible for all those people searching for car shipping services to fill free quote
    request forms. If people are inside car along with you, they’re
    going to feel the tension in the air and you will all wish you shipped the
    automobile instead. It’s critical that when somebody realized the requirement to deliver his
    car, they must start gaining car shipping quotes as soon as they can.

    Annie

    January 9, 2014 at 6:19 am

  30. These services act as an information bank for properties put up on sale.
    This unique type of investigation, this stirring of the mud,is called mindfulness, and is most effectively accomplished
    immediately after coming out of ‘fixed concentration,’ which is that full, bright calm that is experienced when our meditation object disappears and after
    the visions and voices of ‘threshold concentration’
    cease. From Ft Meyers to Naples, restaurants have been eager for
    business.

  31. Make sure the quote includes the subsequent: origin (shipper’s door
    or port), destination (consignee’s door, port or unloading warehouse).
    Your vehicle could possibly be exposed to elements as well as other things while on the ship.

    It’s crucial that when an individual realized the requirement for you his car,
    she must start gaining car shipping quotes as soon
    as he is able to.

    Lizette

    January 12, 2014 at 1:59 am

  32. Suddenly, there is a bright light, and your soul somehow flies higher than the universe itself,
    higher than you could ever even conceive of it flying.
    These investigations into the body and mind will deepen as our
    meditation becomes an ongoing, continuous process all
    day long. That means that although there is another world, it will be so entirely different that we cannot ever speak of
    it.

  33. We must now be responsible and courageous, however,
    investigating to see the actual truth of this body we hold so dear.

    This unique type of investigation, this stirring of the mud,
    is called mindfulness, and is most effectively accomplished
    immediately after coming out of ‘fixed concentration,’ which is that full,
    bright calm that is experienced when our meditation object disappears
    and after the visions and voices of ‘threshold concentration’
    cease. The study also provides much-needed statistical
    support for a claim universally made by arts organizations and public art programs around the country.

    Cleveland

    January 12, 2014 at 5:02 pm

  34. Suddenly, there is a bright light, and your soul somehow flies higher than the universe itself, higher than you could
    ever even conceive of it flying. In my opinion, this is what true learning is about.
    If one is impressed by the tropical climate
    and natural beauty this area has to offer
    then outside attractions might be the key, although the Winter Estates
    is partially outside as well.

  35. In this situation, you need to look for the company that
    has the most reasonable fees. When you’re going to produce
    decision to ship your car or truck in California then
    you certainly must require a idea about the routes of California.
    They protect your automobile while shipping and save you money in the same time.

    Ship My Car

    January 15, 2014 at 5:51 am

  36. I do agree with all the ideas you’ve offered on your post. They’re really convincing and can definitely work. Nonetheless, the posts are too quick for novices. May you please prolong them a little from next time? Thanks for the post.

    Leia Simlick

    November 11, 2016 at 5:54 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: