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="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 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> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </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

springapp-servlet.xml

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

springapp-service.xml

<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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "> <context:annotation-config /> <bean id="userManager" class="springapp.service.UserManagerImpl"> </bean> <bean id="userDao" class="springapp.dao.HibernateUserDao" /> </beans>

springapp-data.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "> <!-- enable declarative transaction management --> <tx:annotation-driven />     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:/hibernate.properties" /> </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.

User

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) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.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) { this.homes = homes; } }

Home

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) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne @JoinColumn(name="user_id") public User getUser() { return user; } public void setUser(User user) { this.user = user; } }

IV. Persistent Layer

HibernateUserDao

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.

UserManaer

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; } }

RequestController

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 hibernate.properties and hibernate.cfg.xml files.

The Eclipse project for this application is available here.




Advertisements
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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s