Using OpenSessionInViewFilter in Spring Web Application

A way too simple Spring 2.5 web application to show how to use OpenSessionInViewFilter together with Hibernate.

I. web.xml configuration

<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="" xmlns:xsi="" xsi:schemaLocation="" version="2.4"> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springapp-service.xml /WEB-INF/springapp-data.xml </param-value> </context-param> <filter> <filter-name>hibernateFilter</filter-name> <filter-class> </filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>*.htm</url-pattern> </filter-mapping>            <servlet> <servlet-name>springapp</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>0</load-on-startup> </servlet>         <servlet-mapping> <servlet-name>springapp</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>     <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

II. Spring related configuration


<beans xmlns="" xmlns:xsi="" xmlns:context="" xsi:schemaLocation=" ">                     <context:component-scan base-package="springapp" /> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> <property name="order" value="0" /> </bean>         <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception"> customError </prop> </props> </property> </bean>   </beans>


<beans xmlns="" xmlns:xsi="" xmlns:context="" xsi:schemaLocation=" "> <context:annotation-config /> <bean id="userManager" class="springapp.service.UserManagerImpl"> </bean> <bean id="userDao" class="springapp.dao.HibernateUserDao" /> </beans>


<beans xmlns="" xmlns:xsi="" xmlns:tx="" xmlns:context="" xsi:schemaLocation=" "> <!-- enable declarative transaction management --> <tx:annotation-driven />     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:/" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${hibernate.connection.driver_class}" /> <property name="url" value="${hibernate.connection.url}" /> <property name="username" value="${hibernate.connection.username}" /> <property name="password" value="${hibernate.connection.password}" /> </bean>       <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" > <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>springapp.domain.User</value> <value>springapp.domain.Home</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> </props> </property> </bean>     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>

II. Domain Model

Domain model only contains two classes: User and Home with a one-to-many relations.


package springapp.domain; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class User { private Long id; private String name; private Set<Home> homes = new HashSet<Home>(); @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { = id; } public String getName() { return name; } public void setName(String name) { = name; } @OneToMany(targetEntity = Home.class, cascade=CascadeType.ALL, fetch = FetchType.LAZY, mappedBy="user") public Set<Home> getHomes() { return homes; } public void setHomes(Set<Home> homes) { = homes; } }


package springapp.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Home { private Long id; private String name; private User user; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { = id; } public String getName() { return name; } public void setName(String name) { = name; } @ManyToOne @JoinColumn(name="user_id") public User getUser() { return user; } public void setUser(User user) { this.user = user; } }

IV. Persistent Layer


package springapp.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.SessionFactoryUtils; import org.springframework.transaction.annotation.Transactional; import springapp.domain.User; public class HibernateUserDao implements UserDao { @Autowired private SessionFactory sessionFactory; @Transactional(readOnly = true) @Override public User findById(Long id) { Session session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE); return (User)session.get(User.class, id); } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }

V. Service Layer

Service layer contains service class to load domain objects and controller class to handle http request.


package springapp.service; import org.springframework.beans.factory.annotation.Autowired; import springapp.dao.UserDao; import springapp.domain.User; public class UserManagerImpl implements UserManager { @Autowired private UserDao userDao; @Override public User getUserById(Long id) { return this.userDao.findById(id); } public void setUserDao(UserDao userDao) { this.userDao = userDao; } }


package springapp.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import springapp.domain.User; import springapp.service.UserManager; @Controller @RequestMapping("/*.htm") public class RequestController { @Autowired private UserManager userManager; @RequestMapping(method = RequestMethod.GET) public ModelAndView handle() {         User user1 = userManager.getUserById(Long.valueOf(1L)); User user2 = userManager.getUserById(Long.valueOf(2L)); Map<String, Object> model = new HashMap<String, Object>(); if (user1 != null) { model.put("user1", user1); } if (user2 != null) { model.put("user2", user2); } return new ModelAndView("users", model); } public UserManager getUserManager() { return userManager; } public void setUserManager(UserManager userManager) { this.userManager = userManager; } }

VI. Test JSP

Once deployed, web application name is “opensessioninview”.

The JSP page to display data is located at /WEB-INF/jsp/users.jsp and URL is http://some.ip.address.and.port/opensessioninview/users.htm.

VII. Download

This application is using MySQL as database, you will need to run two programs first to setup table and data.

  • HibernateUtil.class – to create database table
  • Main.class – to add data and execute a load data function

Remember to change database username and password in the and hibernate.cfg.xml files.

The Eclipse project for this application is available here.

Using OpenSessionInViewFilter in Spring Web Application

4 thoughts on “Using OpenSessionInViewFilter in Spring Web Application

  1. With your project example you have finally resolved my impossible problem with OpenSessionInViewFilter.
    I live in Verona, the city of love, Romeo and Juliet: a day if you decide to come here I can guide you into Verona. Obviously free.
    Have a good day!!

  2. Prakash says:

    great article about how to use springframework’s OpenSessionInViewFilter. I was trying to implement OpenSessionInView Interceptor with no success. But the filter is much easier to configure. thanks very much

Leave a Reply

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

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

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s