Spring MVC Tutorial – Hibernate Integration
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:
- JDK 6 update 16
- Tomcat 6.0.20
- SpringSource Tool Suite 2.2.0 as my IDE
- MySQL 5.1
- 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)
- JSTL 1.2 (from jstl.dev.java.net)
- Hibernate Distribution 3.3.2.GA
- Hibernate Annotations 3.4.0.GA
- log4j 1.2.15
- slf4j 1.5.8
- 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
- Start STS
- Create a Dynamic Web Project from File>New>Other
- Name the project ‘ibank’
- Choose the target runtime – the server on which you’ll be deploying. Create one if already not available.
- Keep everything else default (the source, class and web content directories)
- 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,
- Right-click WebContent in the project explorer and then New>JSP
- Name it index.jsp and accept all defaults
- 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.
- In Project Explorer, right-click Java Resources: src and then click New>Other, select Spring Bean Configuration File
- 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
- 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
- Create ibank-service.xml and ibank-persistence.xml in a similar fashion
- In Project Explorer, expand Spring Elements, right-click Beans and choose Properties. The three files created should be shown in the Config Files tab
- Go to Config Sets tab and click the New button
- Give a name of your choice (I chose ibank-beans), click Select All and then OK
- 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
- Go to Window>Preferences, expand Server node in the tree on the left and select Runtime Environments
- Click Add and choose your Tomcat version (shouldn’t be less than 5.5), click Next
- 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
- Go to Window>Show View>Servers
- Right-click on the Servers panel and choose New>Server
- Select the server type and check if the server runtime environment shows the one created in steps 1-3
- Click Next
- At this point, the IDE will give you an option to make your project available to the created server
- Select your application and click Add, then click Finish
If your controller shows errors with the HttpServlet… classes
- Right-click your project root, select Build Path>Configure Build Path
- Select the Libraries tab
- Click Add Library, then choose Server Runtime and select your Tomcat server
If Tomcat is already configured in your IDE then
- Open the Servers panel (Window>Show View>Servers)
- Right-click your server and choose Add and Remove
- 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).
- Under WEB-INF/jsp, create a new folder named admin
- Create three JSP files: admin.jsp, menu.jsp, and footer.jsp
- Under WebContent folder, create a new CSS file names master.css
- 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″%>
© 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”><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:
- Take out the database connection information out of Hibernate and manage it through Spring.
- 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:
- User clicks on new customer registration link
- System presents new customer input page
- User fills in the details and submits
- System verifies data – omitted from this tutorial
- 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> </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:

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!
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
[...] a comment » In this installment, I’m expanding the project done in Spring MVC Tutorial – Hibernate Integration to [...]
Spring MVC Tutorial – Paging Through Hibernate and Selection Handling « Himu’s Attempt at Blogging
November 26, 2009 at 3:31 pm
[...] Spring MVC Tutorial – Hibernate Integration – build a Spring MVC app using Hibernate from the ground up. [...]
Spring MVC Tutorial – Using Tiles 2 « Himu’s Attempt at Blogging
December 9, 2009 at 2:53 pm
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
Hello Satish,
Customer browsing and authorization is already written under my next post Spring MVC Tutorial – Paging Through Hibernate and Selection Handling
mhimu
December 30, 2009 at 10:15 am
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
how can we view customer list
manoj
August 2, 2010 at 3:32 pm
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
HI Himu,
Its very nice tutorial,able to create spring webapplication very easily…
Thank you
Leela
November 12, 2010 at 12:46 pm
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
It a nice simple tutorial for hibernate with Spring MVS
Santhosh
January 12, 2011 at 6:54 pm
Descriptive tutorial….. If you can post a tutorial utilizing the spring annotation support…
Aneer Indian
February 11, 2011 at 12:42 pm
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
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
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
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
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