I'm currently e开发者_如何学编程xperiencing a LazyInitException with a page containing code like the following:
<h:form>
<ui:repeat value="#{searchBean.storiesByTag}" var="iStory">
<ui:repeat value="{iStory.tags}"var="iTag">
<!-- Lazy init exception here -->
#{iTag.content}
</ui:repeat>
</ui:repeat>
</h:form>
storiesByTag()
is a bean method that retrieves a List
of stories. The second ui:repeat
is supposed to then take each tag and display it's content. All fetching is lazy by default to avoid loading more objects than is necessary.
I'm still fuzzy on this but, from what I understand, this can happen because an EntityManager
is closed (exit from @Transactional
cloud) during a request or a Collection
is being accessed.
Spring's OpenEntityManagerInViewFilter
from Spring has been added to the project but I'm not sure if it's doing it's job correctly. Any suggestions for testing this are welcome.
Since I assume the Collection
is the problem here I'd like to know what would be a good solution. Should I modify a DAO method with a fetch join
? Or should I take the hacky route by using <f:view beforePhaseListener=...>
to trigger a method inside a bean and get some fresh Tag objects from the database?
Edit: For Bozho:
web.xml:
<!-- Open EM in View Filter -->
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- End -->
For Roman:
applicationContext.xml:
<!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
What is the name of your entity manager factory?
From OpenEntityManagerInView docs:
Looks up the EntityManagerFactory in Spring's root web application context. Supports a "entityManagerFactoryBeanName" filter init-param in web.xml; the default bean name is "entityManagerFactory".
If you specified the name different from "entityManagerFactory" then the filter doesn't see your factory.
精彩评论