Tutorial: Spring MVC and Hibernate made simple with Annotations for beginners

Please click one of these quick links to skip to a particular section.

Configuration | ORM Prelim | Controller | Service | DAO | View | Summary | Github clone URL

1. Integrating Hibernate’s configuration into Spring’s application context along with annotation meta data reduces XML configuration.

In a traditional Hibernate application not using Spring, you typically have a Hibernate configuration file and possibly several XML mapping files to map the different tables in your datasource to domain objects.  This tutorial attempts to show you how to integrate Hibernate in a Spring application where most of the Hibernate configuration can be moved to the Spring application context, and simple annotations on domain objects eliminate the need for separate XML mapping files.  Although both methods can coexist.  Combined with Spring’s annotation meta data configuration, this results in minimal XML configuration.

The first thing to configure is the web.xml file and it’s pretty straight forward.  It requires a Spring DispatcherServlet and corresponding servlet mapping.

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

<servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

The next thing to configure will be your minimal web application context for Spring.  I’m posting the full file and will explain what some of the different elements do.

<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:property-placeholder location="classpath:jdbc.properties" />

    <context:component-scan base-package="com.thewebsitehouse" />

    <tx:annotation-driven />

    <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="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.thewebsitehouse.domain.Event</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.connection.pool_size">${hibernate.connection.pool_size}</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

The first thing to take note of are the different Spring schemas.  With Spring having introduced schema based configuration in Spring 2.0, it greatly reduces the amount of XML verbosity in your configuration file, hence this minimal web application context.  The namespaces I’ve made use of are the basic beans namespace as well as the context and tx namespaces.

  • On line 20, we’ve defined a context:property-placeholder element which we use to tell the Spring container where to find some properties files for resolving ${} type placeholders within our application context.
  • On line 22, we’ve defined a context:component-scan element that tells Spring where to begin scanning our package for annotated components like @Repository, @Service, @Controller, etc.  Using this element also automatically implies the context:annotation-config element’s behavior to scan for things like @Autowired and several other annotations.  Therefore you don’t need both elements in your application context.

The tx namespace is responsible for handling our database transactions.  Using the tx:annotation-driven element, we’re telling Spring to look for beans annotated with @Transactional and handle them according to the parameters defined in those annotations.  You’ll also notice on line 58, we’ve defined a TransactionManager implementation bean that gets automatically wired into our annotated configuration for handling the transactions.  Because we named our TransactionManager simply “transactionManager” in our configuration, it automatically gets wired into our annotated configuration, this is the Spring default.  If we had given it a different name, we would have had to add the transaction-manager attribute to the tx:annotation-driven element and specify the id of our TransactionManager implementation bean.

Our TransactionManager defines one property named sessionFactory, which references our sessionFactory bean on line 41.  Our sessionFactory bean is required for Hibernate and more importantly, being an AnnotationSessionFactoryBean, it will allow us to annotate domain objects at the code level, rather than define our mappings to the database tables in separate mapping XML files.  Once again, we’re reducing the amount of XML configuration required.  The sessionFactory bean I’ve defined has three properties.  The first is the dataSource which references our dataSource bean.  The second being annotatedClasses which allows us to list the domain objects we’ve annotated rather than configured XML mapping files for.  The third parameter is the hibernateProperties property.  This allows us to define Hibernate specific properties within our configuration file, rather than in a hibernate configuration XML file.

So the remaining beans are the dataSource (which I mentioned in the previous paragraph) and the jspViewResolver.  The dataSource is pretty straight forward.  We’ve defined a DriverManagerDataSource which allows us to define the driver, url, username and password for our datasource.  We’ve used ${} parameters here that will be replaced by our context:property-placeholder bean.  The jspViewResolver is used by Spring MVC to resolve Controllers to a view.  You can read more about this in the Spring documentation.  With the configuration out of the way, lets move on to our Controller implementation, our service beans and our DAO beans.

2. One of the main reasons for using an ORM framework like Hibernate is to persist domain objects to a datasource without the need for writing cumbersome SQL statements, acquiring connections and cleaning up those connections, etc.  An ORM framework does this for you.

To start, let’s define a domain object to persist.  In this case a calendar event.  Here’s a class definition for an Event object.

package com.thewebsitehouse.web.domain;

import java.util.Date;

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

@Entity
@Table(name = "EVENTS")
public class Event {

	@Id @GeneratedValue
	@Column(name = "EID" )
	private Long id;

	@Column(name = "ETITLE")
	private String title;

	@Column(name = "EDATE")
	private Date date;

	public Event() {}

	public Long getId() {
		return id;
	}

	private void setId ( Long id ) {
		this.id = id;
	}

	public Date getDate() {
		return date;
	}

	public void setDate ( Date date ) {
		this.date = date;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle ( String title ) {
		this.title = title;
	}

	public String toString() {
		return "Title: " + title + ", Date: " + date;
	}

}

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 = “EVENTS”) annotation tells Hibernate which table to map properties in this class to.
  • The first property in this class on line 17 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.  Lastly the @Column(name = “EID”) annotation is used to map this property to the EID column in the EVENTS table.  The other two properties are annotated in the same fashion, but merely with the @Column attribute.

3. Defining an annotated Controller to add Events and list existing Events.

Here is our simple Controller implementation for a Controller which handles creating Events and listing Events.

package com.thewebsitehouse.web;

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

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.thewebsitehouse.web.domain.Event;
import com.thewebsitehouse.web.service.EventService;
import com.thewebsitehouse.web.util.ControllerUtil;

@Controller
@RequestMapping("/events")
public class EventController {

	@Autowired
	private EventService eventService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView saveEvent ( @ModelAttribute("event") Event event, BindingResult result ) {
		ControllerUtil.logBindingErrors ( result );

		eventService.addEvent ( event );

		return new ModelAndView ( "redirect:/events.html" );
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView viewEvents() {
		Map model = new HashMap();
		model.put ( "events", eventService.getAllEvents() );

		return new ModelAndView ( "eventsView", model );
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView addEvent() {
		return new ModelAndView ( "eventAdd" );
	}

}

Glance at the imports for now just to give you an idea of what’s being used, but the important stuff is within the class definition.

  • I’ve annotated the EventController class with @Controller and @RequestMapping(“/events”) on line 18 and 19.  When Spring scans our package, it will recognize this bean as being a Controller bean for processing requests.  The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /events in the URL path.  That includes /events/* and /events.html.
  • An EventService bean will be autowired and injected by Spring since we applied the @Autowired annotation to the private property on line 23. The property name is important because Spring will look for a bean named eventService to inject.
  • Three methods have been defined, all of which are responsible for the different ways we might make requests to this Controller.  The first method named saveEvent is annotated with @RequestMapping(value = “/save”, method = RequestMethod.POST).  The annotation tells Spring that requests to /events/save.html should be processed by this method, but only if the request method is POST.  The method signature annotates one of the parameters with @ModelAttribute(“event”) which has to do with our JSP page, but I’ll talk about that shortly.  The next paramter is a BindingResult paramter which comes into play with validation, but I won’t cover that in this tutorial.  The important part of this method is the eventService.addEvent ( event ) on line 29.  This is a call to our service bean to add our domain object to the datasource when it’s entered in the browser.  On line 31, the method returns a ModelAndView object to resolve the view by logical name.  In this case, we’re saying redirect to /events.html, which will also be handled by this Controller.  You’ll also notice on line 27, I have a utility class for logging the BindingResult errors, but I won’t get into that.  It’s basically a “utility” function that iterates over any errors in BindingResult.
  • The next method viewEvents is basically our default method when a simple GET request is made to /events.html, you can see this by the annotation @RequestMapping(method = RequestMethod.GET) on line 34.  This method creates a Map and adds the data to the map by invoking the eventService.getAllEvents() method on line 37.  That call returns a List object.  The method returns another ModelAndView object, but this time it will try to resolve to a view named eventsView and the data model is being passed back to the browser so we can access the data within the JSP. The logical view name will resolve to “/WEB-INF/jsp/eventsView.jsp” when processed by the jspViewResolver configured in the application context.
  • The last method is simpley addEvent which is annotated with @RequestMapping(value = “/add”, method = RequestMethod.GET).  This tells Spring to process requests to “/events/add.html” with this method and only if it’s a GET request.  The method signature has the first parameter annotated with @ModelAttribute(“event”) again for accessing the data in the JSP and BindingResult for validation. The method simply returns a ModelAndView object with the logical name of a view as the only parameter.

4. At the heart of the business layer is our service classes.

This listing shows the service bean we called in the Controller.

package com.thewebsitehouse.web.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.thewebsitehouse.web.dao.EventDao;
import com.thewebsitehouse.web.domain.Event;

@Service("eventService")
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class EventServiceImpl implements EventService {

	private final Log log = LogFactory.getLog ( EventServiceImpl.class );

	@Autowired
	private EventDao eventDao;

	public EventServiceImpl() {}

	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public void addEvent(Event event) {
		if ( log.isDebugEnabled() )
        	log.debug ( event.toString() );

		eventDao.saveEvent ( event );
	}

	public List<Event> getAllEvents() {
		return eventDao.getAllEvents();
	}

}

This service bean implements the EventService interface which provides our contract of what this implementation will do.  For now it just adds new events and lists existing events.

  • On line 15, the class is annotated with @Service(“eventService”).  This is the meta data that Spring will use when autowiring the eventService property in the Controller created in the previous step.  We’ve explicitly defined the name “eventSerivice” in the annotation’s value, otherwise without it Spring would have named the bean “eventServiceImpl” automatically and the autowiring of this bean in the Controller and other classes would have failed.
  • One line 16, the @Transactional(propagation=Propagation.SUPPORTS, readOnly=true) annotation will be recognized by the tx:annotation-driven element in the application context.  Having placed the annotation at the class level means that all methods in this class by default should adhere to these transaction rules.  propagation=Propagation.SUPPORTS means a transaction isn’t necessary, but if one exists, then the method will run in that transaction.  The readOnly=true attribute is pretty straight forward, by default all data retrieved should be read only.  No writes to the datasource are permitted.
  • On line 22, an EventDao object gets autowired.  That class will deal with the actual ORM framework, in this case, Hibernate.  I’ll explain that next.
  • On line 26, another @Transactional annotation has been applied right at the method level. This time @Transactional(propagation=Propagation.REQUIRED, readOnly=false) tells the transaction manager that this method requires a transaction.  This is defined by the propagation=Propagation.REQUIRED attribute.  The readOnly=false attribute overrides the class level readOnly=true so that we are permitted to write to the datasource.  That’s an important thing to keep in mind.  When you annotate at the class level, the rules are applied to every method, but if you need to override the class level attributes, you can do so by annotating the methods in question, overriding whatever attributes you need to.  In this case, since the method will write to the datasource, we require a transaction and write permissions.
  • I won’t go into too much detail on the rest, but as you can see in either method of this class, we’re interacting with the EventDao object to save an Event and list existing events.

5. Just as important as the service layer, is the DAO layer.  At this layer we will interact directly with Hibernate.

The following listing shows the HibernateEventDao implementation:

package com.thewebsitehouse.web.dao;

import java.util.Date;
import java.util.List;

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

import com.thewebsitehouse.web.domain.Event;

@Repository("eventDao")
public class HibernateEventDao implements EventDao {

	@Autowired
	private SessionFactory sessionFactory;

	public void saveEvent ( Event event ) {
		sessionFactory.getCurrentSession().saveOrUpdate ( event );
	}

	@SuppressWarnings("unchecked")
	public List<Event> getAllEvents() {
		return (List<Event>) sessionFactory.getCurrentSession().createCriteria ( Event.class ).list();
	}

}

  • On line 12, the @Repository(“eventDao”) meta data tells Spring this class is a DAO object and Spring should name it “eventDao” so that it can be properly autowired into the eventService bean from the previous step.
  • On line 16, the Hibernate SessionFactory will be autowired by Spring.  If you remember, the SessionFactory was defined in the application context with the bean id “sessionFactory” and thus Spring will autowire itno this property since it has the same name with the @Autowired annotation.
  • On line 18, the saveEvent method is defined.  It interacts with the session factory by getting the current Hibernate Session and calling the saveOrUpdate method, passing in the Event object that was passed to the method.  If the Event object has an existing ID, Hibernate will attempt to update that record in the datasource, if it’s not found, it will try to insert it.  This is pretty much analogous to a MERGE in straight JDBC, but not all dialects support MERGE, ie: DB2/400.
  • Line 23 defines the DAO method for retrieving existing Events from the datasource.  It only contains 1 simple line.  First the current Session is retrieved from the SessionFactory, and then a Criteria is created from that Session, into which we simply pass the Event.class common name, followed by a call to list().  So what we’ve done is essentially told Hibernate, select all records from the table that Event.class is mapped to, and return all property values of the Event class in the form of a java.util.List object.

The two methods in this DAO object are all that it takes for storing and retrieving Event data from the datasource using Hibernate.

6. The last thing to deal with is our view level, which in this case is a couple JSP files.

First is a listing of eventsView.jsp which is located at /WEB-INF/jsp/eventsView.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css"></link>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Existing Events</title>

</head>

<body>
<h1>Existing Events</h1>
<c:url var="addEventUrl" value="/events/add.html" />
<a href="${addEventUrl}">Add Event</a>

<br /><br />
<c:if test="${!empty events}">
	<table class="table">
		<tr>
			<th>ID</th>
			<th>Title</th>
			<th>Date</th>
		</tr>

		<c:forEach items="${events}" var="event">
		<tr>
			<td><c:out value="${event.id}" /></td>
			<td><c:out value="${event.title}" /></td>
			<td><c:out value="${event.date}" /></td>
		</tr>
		</c:forEach>
	</table>
</c:if>
<c:if test="${empty events}">
	There are currently no events scheduled.
</c:if>
</body>
</html>

The important bits here start on line 16.  Using JSTL, I’ve defined a URL with value “/events/add.html” which will get translated into the context root + /events/add.html ie: something like /hibernate1/events/add.html.  I use that URL that gets generated to create a link on line 17 to the page that allows me to add a new event.  Next I have a JSTL if statement on line 20 that checks if the events object we added to the model is not empty.  The events object was added back in step 3 when we defined a Controller.  If events is not empty, then I’m creating a table and iterating over each item to create a table row.  At the end, on line 37 another if statement checks to see if events is empty, and if it is, then a message gets displayed instead of a table of existing events.

Next is a listing of /WEB-INF/jsp/eventAdd.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Add Event</title>

</head>

<body>
<h1>Add Event</h1>
<c:url var="viewEventsUrl" value="/events.html" />
<a href="${viewEventsUrl}">View Existing Events</a>

<br /><br />
<c:url var="saveEventUrl" value="/events/save.html" />
<form:form modelAttribute="event" method="POST" action="${saveEventUrl}">
	<form:label path="title">Title:</form:label>
	<form:input path="title"/><br />
	<form:label path="date">Date:</form:label>
	<form:input path="date"/><br />
	<input type="submit" value="Save Event" />
</form:form>

</body>
</html>

Similar to the eventsView.jsp listing,  on line 14 a URL is defined using JSTL and then a link on line 15 uses that URL to point to the page listing the existing events.  Below is a simple form using the Spring form tag library.  The important bit is on line 19 where the attribute modelAttribute=”event” will be matched to the @ModelAttribute(“event”) annotation of the method signature in the Controller class.  This allows Spring to try and match the form input fields to properties on the Event object class by name.  The BindingResult if you remember from the method signature will provide any validation errors when trying to convert the input data to the property types of the Event class.

Summary

So to summarize, this tutorial was my attempt at showing you how to integrate Hibernate with Spring to create a Spring MVC application with reduced XML configuration in favor of an annotation driven configuration.  It’s a long enough tutorial, which is why I did not go into explicit detail on every line of code or project build.  If you’re familiar enough with creating a simple web application using Maven, then you shouldn’t have too much trouble replicating this tutorial in your own project.  I will be posting my source to github.com shortly, so stay tuned for the clone URL.

If you haven’t installed the SpringSource Tool Suite into your Eclipse environment, I would recommend it.  It makes certain tasks much simpler, the application context graph view is pretty nice.  It shows you how all your beans are connected to each other and you can double click any of the graph bubbles to dig right into that part of the code.  The graph view even detects beans that have been defined using Spring annotations instead of <bean> elements in the application context.

I would like to extend the opportunity to anyone who wishes to provide feedback or questions.  This was my first attempt at using Hibernate in a Spring project, and I would be happy to try and help if you’re running into any road blocks.

Github clone URL

git clone git://github.com/pgrimard/hibernate1.git 

36 thoughts on “Tutorial: Spring MVC and Hibernate made simple with Annotations for beginners

  1. Great tutorial. I was searching one just like this. It jump-started me quite quickly in Spring 3.0.

    However, it seemed the jdbc.properties file in the code base is missing.

  2. Yeah I didn’t include the jdbc.properties because it contained private information, but in reality, it shouldn’t matter because all the information in that file is environment specific. So you might have something like:

    database.driver=some.driver.class.Name
    database.url=jdbc:valid:url
    database.user=user
    database.password=password

    As for the hibernate properties, those are pretty simple to get from the docs, sorry I don’t have the jdbc.properties file in front of me to get them.

    I’m happy this tutorial helped you get started in Spring 3.0!

  3. Finally a straightforward tutorial on spring mvc – Great work!

    Just a question: I won’t ask you about the content of your jdbc.properties file but I would like to know where to place it inside the project-structure because my application doesn’t seem able to locate my jdbc.properties. :-(

    “org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/jdbc.properties]”

    /Kris

    • The jdbc.properties file just needs to be somewhere on the classpath and your config needs to point to that location. My config says look at classpath:jdbc.properties, which means look in the root of my classpath. I use Maven to build my app, so I place the file in the /src/main/resources directory. When Maven builds my app, the file gets copied to the /WEB-INF/classes directory in my app.

  4. Thanks, I got that part working. Now I’m wondering about how to define the hibernate properties. Is that also a separate file in resources? Seeing as you use ${hibernate.dialect} in your app-config.xml there must be a more specific resource available somewhere in the project, right?

    /Kris

  5. > Using Hibernate with Spring, the standard JPA
    > annotations work just as well and that’s what I’m
    > using here.

    Curious to know the reasons which appeal to use JPA annotations instead of Hibernate Annotations…

    • Honestly I have no preference. This was my first attempt at using any kind of ORM framework and the tutorials and documentation I read used JPA, so I just kept that.

  6. I’ve been doing a project with Spring 3.0,Hibernate 3.x. And i’ve done without paying any attention to those details. This tutorial helped me know about eberything. Thanks a lot for the work, Patrick.

  7. Pingback: Spring 3.0 MVC + Hibernate : Simplified with Annotations – Tutorial « Just another Blog

  8. where is the class EventService and ServiceDao?

    sorry I’m just new in using these..

  9. I have an error in import com.thewebsitehouse.util.ControllerUtil;
    because i dont have a package for this.

    • That import is incorrect. You’re missing the “web” subpackage to “com.thewebsitehouse” so your import should look like this:

      import com.thewebsitehouse.web.util.ControllerUtil;

      • i just copied it in you tutorial.

        and what should put in EventService and EventDao?

      • Thanks for pointing that out. I have corrected it in the tutorial.

        Not sure what you’re asking with regard to the EventService and EventDao interfaces.

  10. Am getting this exception.. I have configured what u have said.. What could be problem… I have gooled it but still am not able to do it..

    org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    org.springframework.orm.hibernate3.AbstractSessionFactoryBean$TransactionAwareInvocationHandler.invoke(AbstractSessionFactoryBean.java:299)
    $Proxy73.getCurrentSession(Unknown Source)
    com.practice.dao.HibernateEventDao.saveEvent(HibernateEventDao.java:27)
    com.practice.service.EventServiceImpl.addEvent(EventServiceImpl.java:41)
    com.practice.controller.EventController.saveEvent(EventController.java:38)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:626)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:150)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:354)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:342)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:763)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:709)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:613)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:536)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

  11. Am gettting exception in this line..

    sessionFactory.getCurrentSession().saveOrUpdate ( event )

    as

    org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    org.springframework.orm.hibernate3.AbstractSessionFactoryBean$TransactionAwareInvocationHandler.invoke(AbstractSessionFactoryBean.java:299)
    $Proxy73.getCurrentSession(Unknown Source)
    com.practice.dao.HibernateEventDao.saveEvent(HibernateEventDao.java:27)

    • Both exceptions you’re getting are the same. It sounds like the SessionFactory bean isn’t being injected into the HibernateEventDao bean properly. Check your bean definitions and make sure you have a bean with id=”sessionFactory” that returns a valid SessionFactory.

  12. Hi Patrick,

    Thanks for the reply..

    I have configured bean like…

    com.practice.dbmapping.Event

    ${hibernate.dialect}
    ${hibernate.show_sql}
    ${hibernate.connection.pool_size}

    And dao class like..

    @Repository(“eventDao”)
    public class HibernateEventDao implements EventDao {

    @Autowired
    private SessionFactory sessionFactory;

    public void saveEvent ( Event event ) {
    sessionFactory.getCurrentSession().saveOrUpdate ( event );

    }

    @SuppressWarnings(“unchecked”)
    public List getAllEvents() {
    return (List) sessionFactory.getCurrentSession().createCriteria ( Event.class ).list();
    }

    }

    Any problem with configuration.. I have configured sessionFactory correctly..

    Still am getting the same exception.. Please help me to solve this problem…

    Thank in advance

  13. my web.xml

    Spring3Hib3

    org.springframework.web.context.ContextLoaderListener

    test
    org.springframework.web.servlet.DispatcherServlet
    1

    test
    *.htm

    /jsp/redirect.jsp

    my Application context.xml

    com.practice.dbmapping.Event

    ${hibernate.dialect}
    ${hibernate.show_sql}
    ${hibernate.connection.pool_size}

    and my test-servlet.xml

    I have tried placing
    this code in applicationContext.xml …

    Since am getting same exception..

    Thankls for the reply..

  14. Hi Patrick …

    Xml file configuration is not placed properly ..
    Please give me ur mail id, I will send my code..

  15. Awesome Tutorial which will help the spring3.0+hibernate buddies a lot. Really superb.
    I was looking for this kind of tutorial. GOT IT. Thanks a Lot

  16. Hey,
    Nice totu, but I can’t use it…

    Have you got the SQL shema tables? or Hibernate will create it automatically? I don’t understand.
    I had some issues with the jdbc.properties, now I fixed it .
    For now my problem is :

    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘patrick.events’ doesn’t exist

    Can you help me?
    Regards

    • My project used an existing DB2/400 database. So I didn’t need Hibernate to create the schema.

      From your exception, it just looks like you don’t have a table named patrick.events. You can use any table you may have and just update the code accordingly.

  17. Hi Patrick, grt post
    Had one question. Why addEvent() method in EventController class has annotated attribute @ModelAttribute(“event”) Event event ? Only the saveEvent() method has some use of Event object. After all the purpose of addEvent seems to be forwarding the user to eventAdd.jsp. Would the example have worked if we remove both parameters of addEvent() method?

  18. Pingback: Happy New Year! « Java Tutorials for Developers

Comments are closed.