Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6329889
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T17:45:43+00:00 2026-05-24T17:45:43+00:00

I have scoured this site among others for answers in getting OpenEntityManagerInViewFilter to work.

  • 0

I have scoured this site among others for answers in getting OpenEntityManagerInViewFilter to work. I have a standard User object that references a roles object with a many to many relationship as a set. When I am try to edit my user from the controller I get the dreaded lazy init exception. For the most part it seems that this should be very trivial to implement by simply adding this to your web.xml:

<filter>
    <filter-name>oemInViewFilter</filter-name>
    <filter-class>
        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
    </filter-class>
</filter>

<filter-mapping>
    <filter-name>oemInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Now to things I have tried without success (these are various suggestions from around the web)

  1. Move the above declaration to very top of the web.xml
  2. Slap @Transactional around my controller method and/or whole class
  3. Obviously switching fetch type to eager works, but defeats my intentions here
  4. Playing with where I have my entityManagerFacorty defined
  5. Verified that OpenEntityManager is present in the lazy init exception, thus its being fired off

About the only thing that I have read that makes sense to me as why this isn’t working is that I am loading two different sessions because of how my persistence layer is set up and the filter is grabbing the wrong one.

Heres the method in my controller where I find a user from the database and causes the lazy init exception because it didn’t retrieve roles from the user object.

@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
   public String edit(@PathVariable final Integer id, final ModelMap modelMap)
   {
      final User user = userDao.find(id); ******This causes the lazy init exception

      if (user != null)
      {
         modelMap.addAttribute("userInstance", user);
         modelMap.addAttribute("validRoles",  new HashSet<Role>(roleDao.findAll()));
         return "/user/edit";
      }
      return "redirect:/user/list";
   }

Here is my relevant setup:

Web.xml:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         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">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/board-servlet.xml  *****This file references the file with entityManager declared*****
            /WEB-INF/board-security.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

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

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

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.png</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.gif</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.ico</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>oemInViewFilter</filter-name>
        <filter-class>
            org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>oemInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>
            com.opensymphony.module.sitemesh.filter.PageFilter
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

board-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

  ****This is what pulls in my entityManager  
 <import resource="classpath:persistence-spring-beans.xml"/> 

    <mvc:annotation-driven/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <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="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="100000"/>
    </bean>

    <bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:message"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

</beans>

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

    <context:annotation-config/>
    <context:component-scan base-package="com.something" use-default-filters="true"/>
    <aop:aspectj-autoproxy proxy-target-class="true"/>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
        <property name="persistenceUnitName" value="prodPersistenceUnit"/>
        <property name="dataSource" ref="c3p0PostgresDataSource"/>
        <property name="packagesToScan" value="com.something.persistence.dto"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <bean id="c3p0PostgresDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="org.postgresql.Driver"/>
        <property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/yellow_hammer"/>
        <property name="user" value="yellow"/>
        <property name="password" value="hammer"/>
        <property name="initialPoolSize" value="3"/>
        <property name="minPoolSize" value="3"/>
        <property name="maxPoolSize" value="50"/>
        <property name="idleConnectionTestPeriod" value="200"/>
        <property name="acquireIncrement" value="1"/>
        <property name="maxStatements" value="0"/>
        <!-- 0 means: statement caching is turned off.  -->
        <property name="numHelperThreads" value="3"/>
        <!-- 3 is default -->
    </bean>
</beans>

Let me know if this isn’t enough relevant information.

EDIT
UserDao – this extends a GenericDao, I’ll post this just below.

@Dao
public class UserDao extends GenericDao<User>
{
   public User findByUsernameAndPassword(final String username, final String password)
   {
      final Query query = entityManager.createQuery("from User user " + "where user.username = :user " + "and user.password = :pass ")
         .setParameter("user", username)
         .setParameter("pass", password);

      return uniqueResult(query);
   }

   public List<User> findByRole(final Role roleIn)
   {
      if (roleIn == null)
      {
         return null;
      }

      final Query query = entityManager.createQuery("select user from User user, Role role where role = :roleParam ").
         setParameter("roleParam", roleIn);

      return query.getResultList();
   }
}

GenericDao

public class GenericDao<T extends BaseDto>
{
   protected Class<T> entityClass;

   @PersistenceContext
   protected EntityManager entityManager;

   public GenericDao()
   {
      final ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
      this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
   }

   public T find(final Integer id)
   {
      return entityManager.find(entityClass, id);
   }

   public List<T> findAll()
   {
      final Query query = entityManager.createQuery("from " + entityClass.getSimpleName());
      return query.getResultList();
   }

   public T save(final T t)
   {
      if (t != null)
      {
         return t.getId() != null && t.getVersion() != null ? update(t) : create(t);
      }

      return null;
   }

   private T create(final T t)
   {
      entityManager.persist(t);
      return t;
   }

   private T update(final T t)
   {
      return entityManager.merge(t);
   }

   public void delete(T t)
   {
      t = entityManager.merge(t);
      entityManager.remove(t);
   }

   protected T uniqueResult(final Query query)
   {
      final List results = query.getResultList();
      if (results.isEmpty())
      {
         return null;
      }
      else if (results.size() == 1)
      {
         return entityClass.cast(results.get(0));
      }

      // TODO send notification, multiple results found
      return null;
   }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T17:45:44+00:00Added an answer on May 24, 2026 at 5:45 pm

    But now!!

    Let me make a guess: the name of your application is: board?

    Correct? then go on and read the remaining answer!

    Yes you have two entity manager, and even two identical application contexts (one app context and one web context) — So you have every bean twice!

    What happened is: you have only one (relevant) spring configuration file:
    ‘board-servlet.xml’ (‘persistence-spring-beans.xml’ is included in that file so at least it is one big logical file)

    And you create a context from this file twice in the ‘web.xml’:

    first:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/board-servlet.xml  *****This file references the file with entityManager declared*****
            /WEB-INF/board-security.xml
        </param-value>
    </context-param>
    ...
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    

    ContextLoaderListener load the application context specified by the files in ‘contextConfigLocation’ parameter.

    second:

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

    Dispatcher Servlet create the web application context, which xml file is:

    • named by the init-param ‘contextConfigLocation’
    • or, if there is no such paramter, it looks for an file named ‘/WEB-INF/-servlet.xml’

    (For more details have a look at the Java Doc of FrameworkServlet)

    In your case there is no explicitly named file, so it reads the ‘board-servlet.xml’ again.

    What you need to do is separate them:

    • remove the <import resource="classpath:persistence-spring-beans.xml"/> from board-servlet.xml
    • change the contextConfigLocation in web.xml that it refers to classpath:persistence-spring-beans.xml and /WEB-INF/board-security.xml direcly
    • (not 100% necessary) separate the ‘context:component-scan’ so that a component scan in board-servlet.xml scan only for @Controller and the component scan in persistence-spring-beans.xml scan for the others (@Service, @Component, @Repository and @Dao)
    • last step: please tell me that it works now
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have scoured the net for this question and have came up empty handed.
I have scoured Google for a tutorial to help with this but haven't been
have written this little class, which generates a UUID every time an object of
I have scoured the internet looking for a solution to this and I am
I have scoured the internet for code that can be used to allow users
I have scoured the web in search of a solution to this problem, but
I have scoured the internet for this answer, and I feel like I keep
I have scoured the Internet far and wide and while I found this stackoverflow
I have scoured the internet looking for an answer to this question and can't
I have scoured the internet but can't find an answer to this : I'm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.