Tutorial:Create Spring 3 MVC Hibernate 3 Example using Maven in Eclipse

Let us make a complete end-to-end application using Spring 3.0 MVC as front end technology and Hibernate as backend ORM technology. For this application we will also use Maven for build and dependency management and MySQL as database to persist the data.

The application will be a simple Contact Manager app which will allow user to add new contacts. The list of contacts will be displayed and user will be able to delete existing contacts.

Our Goal

As describe above, our goal is to create a contact manager application which will allow the user to add a contact or remove it. The basic requirement of the Contact Manager app will be:

  1. Add new contact in the contact list.
  2. Display all contacts from contact list.
  3. Delete a contact from contact list.

Following is the screenshot of end application.
spring3-hibernate-contact-manager

Application Architecture

We will have a layered architecture for our demo application. The database will be accessed by a Data Access layer popularly called as DAO Layer. This layer will use Hibernate API to interact with database. The DAO layer will be invoked by a service layer. In our application we will have a Service interface called ContactService.
spring3-hibernate-application-architecture

Getting Started

For our Contact Manager example, we will use MySQL database. Create a table contacts in any MySQL database. This is very preliminary example and thus we have minimum columns to represent a contact. Feel free to extend this example and create a more complex application.

CREATE TABLE CONTACTS
(
    id              INT PRIMARY KEY AUTO_INCREMENT,
    firstname    VARCHAR(30),
    lastname    VARCHAR(30),
    telephone   VARCHAR(15),
    email         VARCHAR(30),
    created     TIMESTAMP DEFAULT NOW()
);

Creating Project in Eclipse

The contact manager application will use Maven for build and dependency management. For this we will use the Maven Dynamic Web Project in Eclipse as the base architecture of our application.

Download the below source code:
Maven Dynamic Web Project (6.7 KB)

spring3-hibernate-project-structureUnzip the source code to your hard drive and import the project in Eclipse. Once the project is imported in Eclipse, we will create package structure for Java source. Create following packages under src/main/java folder.

  • net.viralpatel.contact.controller – This package will contain Spring Controller classes for Contact Manager application.
  • net.viralpatel.contact.form – This package will contain form object for Contact manager application. Contact form will be a simple POJO class with different attributes such as firstname, lastname etc.
  • net.viralpatel.contact.service – This package will contain code for service layer for our Contact manager application. The service layer will have one ContactService interface and its corresponding implementation class
  • net.viralpatel.contact.dao – This is the DAO layer of Contact manager application. It consists of ContactDAO interface and its corresponding implementation class. The DAO layer will use Hibernate API to interact with database.

Entity Class – The Hibernate domain class

Let us start with the coding of Contact manager application. First we will create a form object or hibernate POJO class to store contact information. Also this class will be an Entity class and will be linked with CONTACTS table in database.
Create a java class Contact.java under net.viralpatel.contact.form package and copy following code into it.

File: src/main/java/net/viralpatel/contact/form/Contact.java

package net.viralpatel.contact.form;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="CONTACTS")
public class Contact {

    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;

    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;

    @Column(name="TELEPHONE")
    private String telephone;

    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
}

The first thing you’ll notice is that the import statements import from javax.persistence rather than a Hibernate or Spring package. Using Hibernate with Spring, the standard JPA annotations work just as well and that’s what I’m using here.

  • First we’ve annotated the class with @Entity which tells Hibernate that this class represents an object that we can persist.
  • The @Table(name = "CONTACTS") annotation tells Hibernate which table to map properties in this class to. The first property in this class on line 16 is our object ID which will be unique for all events persisted. This is why we’ve annotated it with @Id.
  • The @GeneratedValue annotation says that this value will be determined by the datasource, not by the code.
  • The @Column(name = "FIRSTNAME") annotation is used to map this property to the FIRSTNAME column in the CONTACTS table.

The Data Access (DAO) Layer

The DAO layer of Contact Manager application consist of an interface ContactDAO and its corresponding implementation class ContactDAOImpl. Create following Java files in net.viralpatel.contact.dao package.

File: src/main/java/net/viralpatel/contact/dao/ContactDAO.java

package net.viralpatel.contact.dao;

import java.util.List;

import net.viralpatel.contact.form.Contact;

public interface ContactDAO {

    public void addContact(Contact contact);
    public List<Contact> listContact();
    public void removeContact(Integer id);
}

File: src/main/java/net/viralpatel/contact/dao/ContactDAOImpl.java

package net.viralpatel.contact.dao;

import java.util.List;

import net.viralpatel.contact.form.Contact;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class ContactDAOImpl implements ContactDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addContact(Contact contact) {
        sessionFactory.getCurrentSession().save(contact);
    }

    public List<Contact> listContact() {

        return sessionFactory.getCurrentSession().createQuery("from Contact")
                .list();
    }

    public void removeContact(Integer id) {
        Contact contact = (Contact) sessionFactory.getCurrentSession().load(
                Contact.class, id);
        if (null != contact) {
            sessionFactory.getCurrentSession().delete(contact);
        }

    }
}

The DAO class in above code ContactDAOImpl implements the data access interface ContactDAO which defines methods such as listContact(), addContact() etc to access data from database.

Note that we have used two Spring annotations @Repository and @Autowired.

Classes marked with annotations are candidates for auto-detection by Spring when using annotation-based configuration and classpath scanning. The @Component annotation is the main stereotype that indicates that an annotated class is a “component”.

The @Repository annotation is yet another stereotype that was introduced in Spring 2.0. This annotation is used to indicate that a class functions as a repository and needs to have exception translation applied transparently on it. The benefit of exception translation is that the service layer only has to deal with exceptions from Spring’s DataAccessException hierarchy, even when using plain JPA in the DAO classes.

Another annotation used in ContactDAOImpl is @Autowired. This is used to autowire the dependency of the ContactDAOImpl on the SessionFactory.

The Service Layer

The Service layer of Contact Manager application consist of an interface ContactService and its corresponding implementation class ContactServiceImpl. Create following Java files in net.viralpatel.contact.service package.

File: src/main/java/net/viralpatel/contact/service/ContactService.java

package net.viralpatel.contact.service;

import java.util.List;

import net.viralpatel.contact.form.Contact;

public interface ContactService {

    public void addContact(Contact contact);
    public List<Contact> listContact();
    public void removeContact(Integer id);
}

File: src/main/java/net/viralpatel/contact/service/ContactServiceImpl.java

package net.viralpatel.contact.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.viralpatel.contact.dao.ContactDAO;
import net.viralpatel.contact.form.Contact;

@Service
public class ContactServiceImpl implements ContactService {

    @Autowired
    private ContactDAO contactDAO;

    @Transactional
    public void addContact(Contact contact) {
        contactDAO.addContact(contact);
    }

    @Transactional
    public List<Contact> listContact() {

        return contactDAO.listContact();
    }

    @Transactional
    public void removeContact(Integer id) {
        contactDAO.removeContact(id);
    }
}

In above service layer code, we have created an interface ContactService and implemented it in class ContactServiceImpl. Note that we used few Spring annotations such as @Service, @Autowired and @Transactional in our code. These annotations are called Spring stereotype annotations.

The @Service stereotype annotation used to decorate the ContactServiceImpl class is a specialized form of the @Component annotation. It is appropriate to annotate the service-layer classes with @Service to facilitate processing by tools or anticipating any future service-specific capabilities that may be added to this annotation.

Adding Spring MVC Support

Let us add Spring MVC support to our web application.

Update the web.xml file and add servlet mapping for org.springframework.web.servlet.DispatcherServlet. Also note that we have mapped url / with springServlet so all the request are handled by spring.

File: /src/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Spring3-Hibernate</display-name>
	<welcome-file-list>
		<welcome-file>list.html</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

Once the web.xml is configured, let us add spring-servlet.xml and jdbc.properties files in /src/main/webapp/WEB-INF folder.
File: /src/main/webapp/WEB-INF/jdbc.properties

jdbc.driverClassName= com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/ContactManager
jdbc.username=root
jdbc.password=testpass

The jdbc.properties file contains database connection information such as database url, username, password, driver class. You may want to edit the driverclass and dialect to other DB if you are not using MySQL.

File: /src/main/webapp/WEB-INF/spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<context:annotation-config />
	<context:component-scan base-package="net.viralpatel.contact" />

	<bean id="jspViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="classpath:messages" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
		p:location="/WEB-INF/jdbc.properties" />

	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
		p:driverClassName="${jdbc.driverClassName}"
		p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
		p:password="${jdbc.password}" />

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
		<property name="configurationClass">
			<value>org.hibernate.cfg.AnnotationConfiguration</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${jdbc.dialect}</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

	<tx:annotation-driven />
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
</beans>

The spring-servlet.xml file contains different spring mappings such as transaction manager, hibernate session factory bean, data source etc.

  • jspViewResolver bean – This bean defined view resolver for spring mvc. For this bean we also set prefix as “/WEB-INF/jsp/” and suffix as “.jsp”. Thus spring automatically resolves the JSP from WEB-INF/jsp folder and assigned suffix .jsp to it.
  • messageSource bean – To provide Internationalization to our demo application, we defined bundle resource property file called messages.properties in classpath.
    Related: Internationalization in Spring MVC
  • propertyConfigurer bean – This bean is used to load database property file jdbc.properties. The database connection details are stored in this file which is used in hibernate connection settings.
  • dataSource bean – This is the java datasource used to connect to contact manager database. We provide jdbc driver class, username, password etc in configuration.
  • sessionFactory bean – This is Hibernate configuration where we define different hibernate settings. hibernate.cfg.xml is set a config file which contains entity class mappings
  • transactionManager bean – We use hibernate transaction manager to manage the transactions of our contact manager application.

File: /src/main/resources/hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="net.viralpatel.contact.form.Contact" />
    </session-factory>

</hibernate-configuration>

File: /src/main/resources/messages_en.properties

label.firstname=First Name
label.lastname=Last Name
label.email=Email
label.telephone=Telephone
label.addcontact=Add Contact

label.menu=Menu
label.title=Contact Manager
label.footer=&copy; ViralPatel.net

Spring MVC Controller

We are almost done with our application. Just add following Spring controller class ContactController.java to net.viralpatel.contact.controller package.

File: /src/main/java/net/viralpatel/contact/controller/ContactController.java

package net.viralpatel.contact.controller;

import java.util.Map;

import net.viralpatel.contact.form.Contact;
import net.viralpatel.contact.service.ContactService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ContactController {

	@Autowired
	private ContactService contactService;

	@RequestMapping("/index")
	public String listContacts(Map<String, Object> map) {

		map.put("contact", new Contact());
		map.put("contactList", contactService.listContact());

		return "contact";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addContact(@ModelAttribute("contact")
	Contact contact, BindingResult result) {

		contactService.addContact(contact);

		return "redirect:/index";
	}

	@RequestMapping("/delete/{contactId}")
	public String deleteContact(@PathVariable("contactId")
	Integer contactId) {

		contactService.removeContact(contactId);

		return "redirect:/index";
	}
}

The spring controller defines three methods to manipulate contact manager application.

  • listContacts method – This method uses Service interface ContactServer to fetch all the contact details in our application. It returns an array of contacts. Note that we have mapped request “/index” to this method. Thus Spring will automatically calls this method whenever it encounters this url in request.
  • addContact method – This method adds a new contact to contact list. The contact details are fetched in Contact object using @ModelAttribute annotation. Also note that the request “/add” is mapped with this method. The request method should also be POST. Once the contact is added in contact list using ContactService, we redirect to /index page which in turn calls listContacts() method to display contact list to user.
    Related: Forms in Spring MVC
  • deleteContact method – This methods removes a contact from the contact list. Similar to addContact this method also redirects user to /index page once the contact is removed. One this to note in this method is the way we have mapped request url using @RequestMapping annotation. The url “/delete/{contactId}” is mapped thus whenever user send a request /delete/12, the deleteCotact method will try to delete contact with ID:12.

Finally add following JSP file to WEB-INF/jsp folder.

File: /src/main/webapp/WEB-INF/jsp/contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
	<title>Spring 3 MVC Series - Contact Manager | viralpatel.net</title>
</head>
<body>

<h2>Contact Manager</h2>

<form:form method="post" action="add.html" commandName="contact">

	<table>
	<tr>
		<td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
		<td><form:input path="firstname" /></td>
	</tr>
	<tr>
		<td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
		<td><form:input path="lastname" /></td>
	</tr>
	<tr>
		<td><form:label path="email"><spring:message code="label.email"/></form:label></td>
		<td><form:input path="email" /></td>
	</tr>
	<tr>
		<td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
		<td><form:input path="telephone" /></td>
	</tr>
	<tr>
		<td colspan="2">
			<input type="submit" value="<spring:message code="label.addcontact"/>"/>
		</td>
	</tr>
</table>
</form:form>

<h3>Contacts</h3>
<c:if  test="${!empty contactList}">
<table class="data">
<tr>
	<th>Name</th>
	<th>Email</th>
	<th>Telephone</th>
	<th>&nbsp;</th>
</tr>
<c:forEach items="${contactList}" var="contact">
	<tr>
		<td>${contact.lastname}, ${contact.firstname} </td>
		<td>${contact.email}</td>
		<td>${contact.telephone}</td>
		<td><a href="delete/${contact.id}">delete</a></td>
	</tr>
</c:forEach>
</table>
</c:if>

</body>
</html>

Download Source code

Click here to download full source code of Contact manager application (16 KB)

That’s All folks

Compile and execute the Contact manager application in Eclipse.
spring3-hibernate-contact-manager

If you read this far, you should follow me on twitter here.



207 Comments

  • Ankeet Maini wrote on 14 June, 2011, 16:09

    thanks for sharing this piece of info and demonstrating the best integration of spring and hibernate using direct injection of sessionFactory into your DAO.
    :)

  • Charles Owen wrote on 17 June, 2011, 7:07

    Thanks for creating these Spring tutorials. It’s helped me get up to speed with the technologies. This creates a nice foundation I can build on. You must have put a lot of work into it. In every case, I was able to get the examples to work. However, I think the last tutorial, while great, assumes you already have a Maven background. But I eventually got it working. Thanks again for your generous work.

  • Charles Owen wrote on 17 June, 2011, 7:18

    I ran into some issues on the last tutorial with Spring/Maven/Hibernate. I choose to use postgresql instead of mysql. I just find it a more full-featured database. So in order to get the hibernate examples to work, I had to make a few refinements. Postgresql uses sequences to generate incremental numbers, so you have to account for that in your hibernate mapping file. Initially, hibernate was looking for a sequence called hibernate_sequence. I modified the mapping file in order to reference the proper sequence name.

    –jdbc.properties
    jdbc.driverClassName= org.postgresql.Driver
    jdbc.dialect=org.hibernate.dialect.PostgreSQLDialect

    –hibernate.cfg.xml

    –contacts.hbm.xml

    contacts_id_seq

  • Charles Owen wrote on 17 June, 2011, 7:24

    Looks like some of my code is missing….
    –jdbc.properties

    jdbc.driverClassName= org.postgresql.Driver
    jdbc.dialect=org.hibernate.dialect.PostgreSQLDialect
    

    –hibernate.cfg.xml

    <hibernate-configuration>
        <session-factory>
             <mapping resource="contacts.hbm.xml" />
        </session-factory>
    </hibernate-configuration>
    

    –contacts.hbm.xml

     <hibernate-mapping>
     	<class name="net.viralpatel.contact.form.Contact" table="CONTACTS">
        	<id name="id" column="id">
            	<generator class="sequence">
    				<param name="sequence">contacts_id_seq</param>
    			</generator>
            </id>
    		<property name="lastname" type="java.lang.String" column="lastname" />
            <property name="firstname" type="java.lang.String" column="firstname" />
            <property name="telephone" type="java.lang.String" column="telephone" />
            <property name="email" type="java.lang.String" column="email" />
        </class>
    
     </hibernate-mapping>
     
    • Raju wrote on 29 August, 2011, 16:12

      Since the example uses Annotation (without hbm files).. you can use Sequence annotation on Contact class as follows:-
      @SequenceGenerator(name = “contacts_id_seq”, initialValue = 1001)

  • Charles Owen wrote on 17 June, 2011, 7:26

    –jdbc.properties
    jdbc.driverClassName= org.postgresql.Driver
    jdbc.dialect=org.hibernate.dialect.PostgreSQLDialect

    –hibernate.cfg.xml

    –contacts.hbm.xml

    contacts_id_seq

  • Charles Owen wrote on 17 June, 2011, 7:30

    How do you submit a comment that has code with html elements? It appears that the code is being truncated. I didn’t know if there was a special or pre tag we’re supposed to use.

  • selmen wrote on 24 June, 2011, 20:25

    Hi all
    Thanks for the tut
    I’m not familar with MAVEN so i encountred many dependency problem
    it’s possible de to do run this tutorial without using maven?
    Can i just import the needed jars ?
    Could some give me the list of the jars to be imported (if possible with the exact virsion number)
    Thank you for your help

  • mallikarjun wrote on 5 July, 2011, 14:58

    Hi, i am trying same application , But it is giving this error

    The requested resource (/SpringAppliaction/delete/3) is not available.

    even in addcontact() also if i give redirect:/index
    shwing error like resource is not available
    I am thinking that my application is not supporting RESTFull URLs.
    IS that the problem?
    could you pleas e reslove my problem.

  • James wrote on 10 July, 2011, 6:46

    Hi, I am trying out this tutorial as well, however, I got the error msg at the end of this post when I open “https://localhost:8443/Spring3Hibernate/index” in my browser (FF).
    My AP server is WASCE 2.1 (geronimo-like), and I put “-Xms512m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled” into geronimo.bat as follows:
    %_EXECJAVA% %JAVA_OPTS% -Xms512m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled %GERONIMO_OPTS% -sourcepath “%JDB_SRCPATH%” -Djava.endorsed.dirs=”%GERONIMO_HOME%\lib\endorsed;%JRE_HOME%\lib\endorsed” -Djava.ext.dirs=”%GERONIMO_HOME%\lib\ext;%JRE_HOME%\lib\ext” -Dorg.apache.geronimo.home.dir=”%GERONIMO_HOME%” -Djava.io.tmpdir=”%GERONIMO_TMPDIR%” -classpath %_JARFILE% %MAINCLASS% %CMD_LINE_ARGS%

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: java.lang.OutOfMemoryError: PermGen space
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:268)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:806)

    root cause

    java.lang.OutOfMemoryError: PermGen space
    org.eclipse.jdt.internal.compiler.parser.Parser.createJavadocParser(Parser.java:7827)
    org.eclipse.jdt.internal.compiler.parser.Parser.(Parser.java:886)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:806)

    note The full stack trace of the root cause is available in the Apache Geronimo(Embedded Tomcat/6.0.29) logs.

  • naveen wrote on 20 July, 2011, 16:31

    excellent …….thnx

    • subair wrote on 4 January, 2012, 17:33

      i am getting 404 error i am trying for long time i am new to spring and maven i am also trying to solve it but i cant i hav added al lib its coming as resources not found could any one help me out

  • Frank wrote on 21 July, 2011, 18:53

    Hi

    I get an stange error. I get to the point where I am supposed to add contact…after filling out the textboxes and pressing “Add Contact” I get the following error:

    com.mysql.jdbc.JDBC4PreparedStatement@b8fba5: insert into CONTACTS (EMAIL, FIRST
    NAME, LASTNAME, TELEPHONE, ID) values (‘frs@klp.no’, ‘Frank’, ‘Sorensen’, ’90185
    975′, ** NOT SPECIFIED **)
    21.jul.2011 15:40:32 org.hibernate.util.JDBCExceptionReporter logExceptions
    WARNING: SQL Error: 0, SQLState: 07001
    21.jul.2011 15:40:32 org.hibernate.util.JDBCExceptionReporter logExceptions
    SEVERE: No value specified for parameter 5

    Any ideas?

    Br

    Frank

    • Viral Patel wrote on 22 July, 2011, 12:13

      @Frank – Check if the created column in table CONTACTS has default value now(). You may want to remove this column for testing your code.

  • leon wrote on 8 August, 2011, 9:48

    when i copy the codes importing javax, it is not found by my IDE. i use spring source tool suite. what should i do?

    • miszczu wrote on 10 August, 2011, 0:32

      Add depedency using maven

  • leon wrote on 8 August, 2011, 12:18

    in the jsp files, are these lines really necessary?

    as well as these tlines? which are located inside the spring-servlet.xml

  • akhtar wrote on 9 August, 2011, 15:06

    hey… i tried this example. but getting 404 not found error.

  • mahesh wrote on 17 August, 2011, 15:30

    Excellent …

  • Tom wrote on 17 August, 2011, 18:03

    I got 404 also, why is welcome file list.html, when we do not have that file, nor we have mapping for it in controller? How to fix?

  • Nish wrote on 28 August, 2011, 10:07

    good tutorial , thx..please add , how to deploy the project in application server ( tomcat , jboss ,,etc )

  • Tony wrote on 9 September, 2011, 20:41

    Note that when running as server application from eclipse the web browser will point to
    http://localhost:8080/Spring3HibernateMaven/
    and not
    http://localhost:8080/Spring3HibernateMaven/index

  • vvk wrote on 16 September, 2011, 20:10

    I am getting a Hibernate mapping exception as follows.

    java.lang.Throwable: Substituted for missing class org.hibernate.MappingException – An AnnotationConfiguration instance is required to use

    I am not able to fix it.

  • Kamal wrote on 21 September, 2011, 21:00

    Hi,
    1) When you said :
    Unzip the source code to your hard drive and import the project in Eclipse.
    Did you mean :
    File–> Import–>Maven–>Existing Maven Projects ?

    Where are the jars ? the pom.xml has only one dependency :

    javax.servlet
    servlet-api
    2.5

    where are the others (spring, hibernate,….) ?

    Thanks, your help is appreciated.

  • kalyani wrote on 27 September, 2011, 17:13

    Can you please share the list of JARs used for the above “Tutorial:Create Spring 3 MVC Hibernate 3 Example using Maven in Eclipse”. I tried the above tutorial, but getting a number of ClassNotFound exception. I am using spring-framework-3.0.6.RELEASE & hibernate-search-3.4.0.Final-dist

  • Dipak wrote on 30 September, 2011, 16:02

    Hi,

    I got following error once i had run on tomcat 6.0/java6.1
    Please let me know whats could be the causes.

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactController’: Injection of autowired dependencies failed; nested exception is bean with name ‘contactDAOImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory net.viralpatel.contact.dao.ContactDAOImpl.sessionFactory; nested exception is java.lang.NoClassDefFoundError: Ljavax/transaction/TransactionManager;
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
    java.lang.Thread.run(Unknown Source)

    Thanks,
    Dipak.

    • Viral Patel wrote on 3 October, 2011, 11:58

      @Deepak: It seems to be a classpath or missing jar file issue. The error says “NoClassDefFound: Ljavax/transaction/TransactionManager;”. Check if you have all the required jar file mentioned in this article in your classpath.

  • eugen wrote on 2 October, 2011, 5:09

    Hi!
    How can i resolve such a problem:
    Description Resource Path Location Type
    The container ‘Maven Dependencies’ references non existing library ‘C:\…..\.m2\repository\org\hibernate\hibernate-entitymanager\3.3.2.ga\hibernate-entitymanager-3.3.2.ga.jar’ Spring3HibernateMaven Build path Build Path Problem

  • Dipak wrote on 3 October, 2011, 17:38

    Hi Viral,

    Thanks For your reply.

    But i didn’t find lib jar file list for this project.
    can you provide me all required jar file list.

    THanks,
    Dipak.

    • Viral Patel wrote on 3 October, 2011, 22:50

      @Dipak, download the source code from above tutorial. The dependencies are managed using Maven. Check the pom.xml in the downloaded source.

  • eugen wrote on 4 October, 2011, 5:04

    Hi!
    I resolved the problem with entitymanager-3.3.2.ga by just adding this jar into repository file, but I still have HTTP Status 500 – error:
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.service.ContactService net.viralpatel.contact.controller.ContactController.contactService;

    Caused by: java.lang.NoSuchMethodError: org.slf4j.impl.StaticLoggerBinder.getSingleton()Lorg/slf4j/impl/StaticLoggerBinder;

    java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.AnnotationConfiguration

    I have added all possible jar. files into WEB-INF/lib
    Thanks,
    Eugen

    • eugen wrote on 5 October, 2011, 2:40

      Does anybody know how to fix it?

      • Viral Patel wrote on 5 October, 2011, 21:44

        @Eugen – From the error log it seems that the slf4j jar is not available in classpath.. Check the dependencies again, see if the correct version of this jar is available in your classpath.

        • eugen wrote on 6 October, 2011, 17:06

          Hi Viral!
          Thanks for your answer. The problem was in slf4j libraries. I used two libraries with different slf4j versions. Now the applications is working on eclipse local tomcat server, but i cannot deploy on the real internet server by build.xml . I ve got these errors after deploying on server:
          [javac] Compiling 6 source files to C:\eclipseprojects2\Spring3HibernateMaven\WEB-INF\classes
          [javac] C:\eclipseprojects2\Spring3HibernateMaven\src\main\java\net\viralpatel\contact\controller\ContactController.java:8: package org.springframework.beans.factory.annotation does not exist
          [javac] import org.springframework.beans.factory.annotation.Autowired;
          [javac] ^
          [javac] C:\eclipseprojects2\Spring3HibernateMaven\src\main\java\net\viralpatel\contact\controller\ContactController.java:9: package org.springframework.stereotype does not exist
          [javac] import org.springframework.stereotype.Controller;
          [javac] ^
          [javac] C:\eclipseprojects2\Spring3HibernateMaven\src\main\java\net\viralpatel\contact\controller\ContactController.java:10: package org.springframework.validation does not exist
          [javac] import org.springframework.validation.BindingResult;
          [javac] ^
          [javac] C:\eclipseprojects2\Spring3HibernateMaven\src\main\java\net\viralpatel\contact\controller\ContactController.java:11: package org.springframework.web.bind.annotation does not exist
          [javac] import org.springframework.web.bind.annotation.ModelAttribute;
          [javac] ^
          [javac] C:\eclipseprojects2\Spring3HibernateMaven\src\main\java\net\viralpatel\contact\controller\ContactController.java:12: package org.springframework.web.bind.annotation does not exist
          [javac] import org.springframework.web.bind.annotation.PathVariable;
          [javac] ^
          [javac] C:\eclipseprojects2\Spring3HibernateMaven\src\main\java\net\viralpatel\contact\controller\ContactController.java:13: package org.springframework.web.bind.annotation does not exist
          [javac] import org.springframework.web.bind.annotation.RequestMapping;
          [javac] ^
          [javac] C:\eclipseprojects2\Spring3HibernateMaven\src\main\java\net\viralpatel\contact\controller\ContactController.java:14: package org.springframework.web.bind.annotation does not exist
          [javac] import org.springframework.web.bind.annotation.RequestMethod;
          [javac] ^
          [javac] C:\eclipseprojects2\Spring3HibernateMaven\src\main\java\net\viralpatel\contact\controller\ContactController.java:16: cannot find symbol
          [javac] symbol: class Controller
          [javac] @Controller

          It seems that application cannot find libraries added in WEB-INF/lib file. Can you tell me how to fix this problem.

  • Nikunj wrote on 4 October, 2011, 9:57

    Hi Viral,

    Thanks for the excellent tutorial…

    After the creation of WAR file, I want to deploy it on WAS in RAD7.5 ,,,

    But not able to … Can you pls guide how

    Nik

  • Sunder wrote on 11 October, 2011, 1:45

    Thanks a lot for providing a very good illustration of Annotation Driven Spring Hibernate integration.

  • eugen wrote on 17 October, 2011, 16:09

    Hi Viral!
    Can you tell me, why can’t i add another jsp file to my project by creating new request mapping in Controller and adding a link on the first jsp file?

    Admin page

    @RequestMapping(“/admin”)
    public String listAdmins(Map map) {

    map.put(“admin”, new Post());
    map.put(“adminList”, adminService.listPost());

    return “admin”;
    I get always 404 response
    The requested resource (/admin) is not available.

    • Viral Patel wrote on 18 October, 2011, 9:22

      @Eugen – there can be several reasons why you getting 404 error. Check your web.xml and see which URi have you mapped DispatcherServlet with. Mostly we map *.html. So next try to call /admin.html instead of /admin. Let me know if that helps.

      • eugen wrote on 18 October, 2011, 16:28

        list.html

        spring

        org.springframework.web.servlet.DispatcherServlet

        1

        spring
        /

      • Kiran wrote on 23 October, 2011, 4:52

        Hi Viral,
        thank you for the excellent tutorial.
        I finally made it work after tweaking the maven pom file little bit ( for some reason hibernate-entititymagere3.2.0.GA was not pulling the transitive dependencies). So just added those missing jars manually to pom file. Any ways, it is working now.

        However, Please help me in understanding one thing I can not understand. To run the project I had to give the URL as
        http://localhost:8080/Spring3HibernateMaven/index.
        But I do not see any where we have created index.html . So, my question is how does that URL drives the application ?
        -Kiran

        • Viral Patel wrote on 23 October, 2011, 11:03

          Hi Kiran, Check the web.xml in your project. The Spring’s DispatcherServlet is mapped with URi *.html. Thus any user request with .html will be forwarded to Spring servlet which in turns map “ïndex” with appropriate controller’s method.

          I would recommend you this article: Introduction to Spring 3 MVC

          • Kiran wrote on 23 October, 2011, 20:46

            Thanks Viral. But the web.xml has this content not quite the way you answered. Am I missing something ?

            list.html

            spring

            org.springframework.web.servlet.DispatcherServlet

            1

            spring
            /

          • Kiran wrote on 24 October, 2011, 1:00

            Hi Viral,
            The confusion is coming here ( I see couple of other people experienced the same issues as me ) because In your finished code zip file, index.jsp file is NOT defined.
            I followed these steps to make it work.
            1) created webapp/list.jsp file with the following content
            “”
            2) And then added these lines in the web.xml file.
            “list.jsp”
            With these changes’ one can use the following URL to drive the application.
            http://localhost:8080/Spring3HibernateMaven/

            No need to add index to the URL.

            -Kiran

  • eugen wrote on 18 October, 2011, 16:30

    servlet-mapping
    servlet-name>spring
    url-pattern>/</url-pattern
    servlet-mapping

  • John Seals wrote on 25 October, 2011, 1:38

    Great article! I have one complaint however. It would be nice if you listed all of the jars required to get it to run. It took me a bit to gather them all and get them running. But overall this is nice. I learned a lot.

  • John Seals wrote on 25 October, 2011, 7:53

    One more comment for those struggling with the tutorial. I kept running into maven dependency issues with the Hibernate jars. So I edited the pom.xml file as follows:

    Replace this entry:

    org.hibernate
    hibernate-entitymanager
    3.3.2.ga

    With this:

    org.hibernate
    hibernate-core
    3.3.1.GA

    org.hibernate
    hibernate-annotations
    3.4.0.GA


    javassist
    javassist
    3.4.GA

    org.slf4j
    slf4j-log4j12
    1.5.2

    In case this doesn’t show properly you can read about this fix here:
    https://forum.hibernate.org/viewtopic.php?p=2395418

    All of your Maven problems should go away. Also don’t forget to name your MySQL database “ContactManager” or change jdbc.properties to point to the name of the one you create.

  • GM WIgginton wrote on 26 October, 2011, 21:00

    Hello:
    I’m some what of a newbie with this, but I’m having problems getting your example:
    http://viralpatel.net/blogs/2010/11/spring3-mvc-hibernate-maven-tutorial-eclipse-example.html

    to work with multiple domain entities. I keep getting this in the log at the end of the error stack:
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.frannet.franinfo.service.MarketService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)

    I have two domain entiity objects: State and Market.
    I suspect that the hibernate file needs another session-factory created?

    thanks,
    Ken

  • ozgun bayrak wrote on 2 November, 2011, 19:41

    if you want access to http://localhost:8080/Spring3HibernateMaven/ without “index”
    you need to change “/index” with this “/” (remove index) in ContactController.java file

  • Oliver wrote on 7 November, 2011, 2:09

    Excellent tutorial! Thanks!

  • kevin Chikhaoui wrote on 9 November, 2011, 18:06

    Excellent Tutorial. Thank you :)
    I have a little problem when I run the project:
    ATTENTION: No mapping found for HTTP request with URI [/Spring3HibernateMaven/list.html] in DispatcherServlet with name ‘spring’
    j’ai un petit caniche
    Thank you for your help :)

  • Gurmeet wrote on 15 November, 2011, 7:23

    This is a very informative article. Thank you!

    I do have a question:
    I am implementing a project on the similar lines as your example. However, I am stuck with this error:
    org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation ‘mandatory’

    I am using Spring 3 with Hibernate 3.x. I have a Service class (in the processors package) which gets the Autowired DAO. The Service class has a save method that is marked as @Transactional, but somehow it seems like Spring is not able to initiate the transaction and hence the DAO marked with @Transactional(Mandatory) blows up.
    Here is my root-context.xml file:

    profile.hbm.xml

    hibernate.dialect=org.hibernate.dialect.HSQLDialect
    hibernate.show_sql=true

    • spruser wrote on 29 November, 2011, 21:32

      @Gurmeet. Does you @Transaction(Propagation.REQUIRED) works? I guess it does not, because in my case both works. I think you have not injected sessionFactory to transactionManager bean. Add these to the place where you have added your dataSource (Of course add tx and aop in beans section of configuration).

      And classes where you add @Transaction should be scanned for @Repository using

      You can add this is yourservlet-servlet.xml file.

  • Mihai wrote on 29 November, 2011, 14:01

    Short and good article

  • Nikhil wrote on 1 December, 2011, 18:15

    Please list the jars atleast in comments section

    • sukehndu wrote on 4 December, 2011, 12:53

      configure the project in eclipse and try to build.It will give all the missing jars.

  • Wayne Allan (@WayneAllanDev) wrote on 12 December, 2011, 12:00

    Loved the tutorial. Would be great to see a follow up to this where you add a couple of extra tables/objects with some one-to-many relationships in the database and bring them all together to display and submit in a form.
    I haven’t had much luck myself trying to merge this tutorial with the Hibernate One To Many Annotation tutorial.

  • Marty wrote on 12 December, 2011, 15:10

    Have any of you guys tried this using Hibernate 4? It appears that the “configurationClass” property of org.springframework.orm.hibernate4.LocalSessionFactoryBean no longer exists and is causing my version of the tutorial to not work.

    Hibernate3: http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/orm/hibernate3/LocalSessionFactoryBean.html

    Hibernate4:
    http://static.springsource.org/spring/docs/3.1.0.RC1/javadoc-api/org/springframework/orm/hibernate4/LocalSessionFactoryBean.html

    Does anybody know how to get passed this? Thanks so much!

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ‘configurationClass’ of bean class [org.springframework.orm.hibernate4.LocalSessionFactoryBean]: Bean property ‘configurationClass’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

  • Sam wrote on 22 December, 2011, 21:51

    I am trying to run this tutorial and getting the following error at run time.
    Can someone help?

    java.lang.NoSuchMethodError: org/springframework/web/bind/annotation/support/HandlerMethodResolver.(Ljava/lang/Class;)V
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodResolver.(AnnotationMethodHandlerAdapter.java:399)

    Thank you
    Sam

    • Viral Patel wrote on 22 December, 2011, 23:40

      @Sam – Please check the version of Spring framework included in your web project. It seems the jar file version isn’t correct.

      • Sam wrote on 23 December, 2011, 0:34

        Thanks Viral,

        I am using Spring 2.5.6. Is this compatible with this tutorial?

        • Viral Patel wrote on 23 December, 2011, 0:57

          Hi Sam, You need to use Spring 3.0 for this tutorial. Download the source code and check the maven’s pom.xml.

  • Sam wrote on 23 December, 2011, 2:15

    Viral I updated my lib to 3.0.7 and all the dependency now I am getting following error during the deploy in to web logic 10.3.3.

    [exec] Caused by: weblogic.deploy.api.tools.deployer.DeployerException: Task 82 failed: [Deployer:149026]deploy application springapp on AdminServer.
    [exec] Target state: deploy failed on Server AdminServer
    [exec] java.lang.reflect.MalformedParameterizedTypeException
    [exec] at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:42)

  • Venkee wrote on 27 December, 2011, 17:12

    when i deploy the project, it comes 404 error, how to fix this problem

  • Venkee wrote on 27 December, 2011, 17:14

    Hi Viralpatel,
    i m new in eclipse IDE
    how to add jar files in eclipse(spring & hibernate)

  • rolandl wrote on 31 December, 2011, 7:10

    Hi !

    Using your exemple, I have the same error as GM WIgginton :
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [fr.exchangeit.service.ConsoleService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    Someone know how to fix it ?

    • Viral Patel wrote on 31 December, 2011, 13:40

      @Rolandl – It seems that you changed the package of services to fr.exchangeit.service. Did you also updated the component-scan attribute in spring-servlet.xml?
      If not then update your spring-servlet and add following entry:

       <context:component-scan base-package="fr.exchangeit" />
      
  • timw wrote on 31 December, 2011, 16:50

    Thanks for the great tutorial. Instead of using Eclipse for deployment, I just managed to get this deployed on a standalone JBoss 6.1.0 server. If anyone’s interested I had to jump through the following hoops:

    1. Don’t include Hibernate in the WAR file. Set the Maven scope in the dependency to “provided”. This is avoid some errors when deploying (as JBoss already has Hibernate jars included).

    2. Had to upgrade to Spring version 3.1.0.RELEASE due to a change in JBoss 6 vfs. The latest version of Spring handles this (actually it may have been fixed in 3.0.3). Either way 3.1.0 works.

    3. You can get Hibernate to automatically create the database table by adding:
    create-drop
    to the hibernateProperties in the SessionFactory configuration in spring-servlet.xml

    4. To actually access the application in my browser, I had to point it to:
    http://localhost:8080/Spring3HibernateMaven-0.0.1-SNAPSHOT/index
    because I didn’t specify a context root for the webapp, and it defaults to the name of the WAR file.

    • timw wrote on 31 December, 2011, 16:52

      just noticed the bit about the hibernate config left out the property name due to angle-brackets. the property you need to set is: hibernate.hbm2ddl.auto=create-drop

      Tim

  • subair wrote on 5 January, 2012, 15:43

    i am getting this error could any one help me out plssssssssssssss
    HTTP Status 500 –

    ——————————————————————————–

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: Servlet.init() for servlet spring threw exception

    root cause

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.service.ContactService net.viralpatel.contact.controller.ContactController.contactService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactServiceImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.dao.ContactDAO net.viralpatel.contact.service.ContactServiceImpl.contactDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactDAOImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory net.viralpatel.contact.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.AnnotationConfiguration
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
    root cause

    org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.service.ContactService net.viralpatel.contact.controller.ContactController.contactService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactServiceImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.dao.ContactDAO net.viralpatel.contact.service.ContactServiceImpl.contactDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactDAOImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory net.viralpatel.contact.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.AnnotationConfiguration
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:507)
    root cause

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactServiceImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.dao.ContactDAO net.viralpatel.contact.service.ContactServiceImpl.contactDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactDAOImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory net.viralpatel.contact.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.AnnotationConfiguration
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
    root cause
    org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.dao.ContactDAO net.viralpatel.contact.service.ContactServiceImpl.contactDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactDAOImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory net.viralpatel.contact.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.AnnotationConfiguration
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:507)
    root cause

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactDAOImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory net.viralpatel.contact.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.AnnotationConfiguration
    java.lang.Thread.run(Thread.java:619)
    root cause

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.AnnotationConfiguration
    root cause
    java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.AnnotationConfiguration
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

    • Viral Patel wrote on 5 January, 2012, 16:17

      @Subair: Please check if all the JAR files are in your project’s classpath. And also if all the classes like Controller, Service, DAO have Getter and Setter methods.

  • Jan Petzold wrote on 12 January, 2012, 21:21

    This is really well written. But I also couldn’t get it running. Which Hibernate version is used for this? I tried 3.6.9, it always fails:

    Error creating bean with name ‘contactController’: Injection of autowired dependencies failed

  • Pawan wrote on 13 January, 2012, 16:34

    Hi Virat,
    I tried to build and run this application, I am always getting 404.. I tried the changes you metioned above like changing /index to /index.html.. but no luck.. could you please let me me if I am missing something

  • timmy2000 wrote on 13 January, 2012, 17:43

    Hi Viral, first of all: thanks for this tutorial!
    But I keep getting the same error as subair – every class has getter and setter methods, but it still won’t work…

Leave a Reply

Your email address will not be published. Required fields are marked *

*