Hibernate集合与任何会话无关

我在SO上找到了关于这个问题的几个问题和答案,但它们似乎都涵盖了问题的一个主要原因:在事务之外或在另一个事务中获取集合。 但在我的情况下,我在获取父对象和集合时在同一事务中获取。

@Service @Transactional public class IntegrationServiceImpl implements IntegrationService { @Override public Integration getIntegrationByIdFetchBackendParameters(Long integrationId) { Integration integration = integrationDao.get(integrationId); //not all integrations have to have backend. if (integration.getBackend() != null) { Hibernate.initialize(integration.getBackend().getBackendParameters()); } return integration; } ... 

但是当谈到Hibernate.initialize这个分支在org.hibernate.collection.internal.AbstractPersistentCollection中被执行

 if ( session == null ) { throw new HibernateException( "collection is not associated with any session" ); } 

我不明白为什么sessionnull 。 有人会解释这个并提出解决方案吗?

编辑1 – 完整堆栈跟踪

 org.hibernate.HibernateException: collection is not associated with any session at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:676) at org.hibernate.Hibernate.initialize(Hibernate.java:77) at com.dhl.finFw.service.IntegrationServiceImpl.getIntegrationByIdFetchBackendParameters(IntegrationServiceImpl.java:169) at com.dhl.finFw.web.integration.IntegrationOverviewManagedBean.loadIntegration(IntegrationOverviewManagedBean.java:59) at com.dhl.finFw.web.integration.AbstractIntegrationManagedBean.initCommonFields(AbstractIntegrationManagedBean.java:69) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:344) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:295) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:130) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:399) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1481) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:333) at com.dhl.finFw.spring.scope.ViewScope.get(ViewScope.java:30) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:329) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117) at org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:56) at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176) at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203) at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:72) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185) at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109) at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:68) at org.apache.el.parser.AstValue.getValue(AstValue.java:161) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185) at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109) at com.sun.faces.facelets.tag.jstl.core.ForEachHandler.apply(ForEachHandler.java:161) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95) at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:166) at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93) at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:320) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:379) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:358) at com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199) at com.sun.faces.facelets.tag.ui.IncludeHandler.apply(IncludeHandler.java:120) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95) at com.sun.faces.facelets.tag.ui.DefineHandler.applyDefinition(DefineHandler.java:106) at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:178) at com.sun.faces.facelets.impl.DefaultFaceletContext$TemplateManager.apply(DefaultFaceletContext.java:395) at com.sun.faces.facelets.impl.DefaultFaceletContext.includeDefinition(DefaultFaceletContext.java:366) at com.sun.faces.facelets.tag.ui.InsertHandler.apply(InsertHandler.java:111) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95) at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137) at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:187) at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95) at com.sun.faces.facelets.tag.jsf.core.ViewHandler.apply(ViewHandler.java:179) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95) at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93) at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:320) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:379) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:358) at com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199) at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:155) at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93) at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87) at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:164) at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:870) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.dhl.finFw.web.filter.FileNotFoundFilter.doFilter(FileNotFoundFilter.java:40) at com.dhl.finFw.web.filter.FileNotFoundFilter.doFilter(FileNotFoundFilter.java:35) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:64) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:724) 

编辑2 – 配置

              ${finFw.config.location}finFwUI.properties classpath:application.properties classpath:dateTime.properties                                           

web.xml中

   FinFwUI Financial Framework Configuration  Faces Servlet javax.faces.webapp.FacesServlet 1   fileServlet com.dhl.finFw.web.FileServlet    log4jConfigLocation ${finFw.config.location}log4j-finFwUI.properties    applicationVersion ${applicationVersion}   primefaces.THEME dhl   javax.faces.FACELETS_SKIP_COMMENTS true   javax.faces.FACELETS_LIBRARIES /WEB-INF/springsecurity.taglib.xml    javax.faces.PROJECT_STAGE ${finFwUI.jsf.stage}    contextConfigLocation  classpath:com/dhl/finFw/finFwUI-core.xml classpath:com/dhl/finFw/finFwUI-dataSource.xml classpath:com/dhl/finFw/finFwUI-security.xml classpath:com/dhl/finFw/finFwUI-forms.xml classpath:com/dhl/finFw/finFwUI-audit.xml  </context-  javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE true   60    org.springframework.web.util.Log4jConfigListener    org.springframework.web.context.ContextLoaderListener   org.springframework.web.context.request.RequestContextListener   org.springframework.security.web.session.HttpSessionEventPublisher   Faces Servlet /faces/*   Faces Servlet *.faces   Faces Servlet *.xhtml   fileServlet /file/*   /pages/protected/index.xhtml   encoding-filter org.springframework.web.filter.CharacterEncodingFilter  encoding UTF-8   forceEncoding true    springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy   fileNotFoundFilter com.dhl.finFw.web.filter.FileNotFoundFilter   browserCacheControlFilter com.dhl.finFw.web.filter.BrowserCacheControlFilter   PrimeFaces FileUpload Filter org.primefaces.webapp.filter.FileUploadFilter   PrimeFaces FileUpload Filter Faces Servlet   springSecurityFilterChain /*   encoding-filter /*   fileNotFoundFilter /*   browserCacheControlFilter /pages/protected/integration/subscriptionScheduler.xhtml   org.springframework.security.access.AccessDeniedException /pages/public/error/accessDenied.xhtml   java.lang.Throwable /pages/public/error/internal.xhtml   500 /pages/public/error/internal.xhtml   404 /pages/public/error/notFound.xhtml   403 /pages/public/error/accessDenied.xhtml   

ViewScope.java

 public class ViewScope implements Scope { private Logger logger = LoggerFactory.getLogger(getClass()); public static final String VIEW_SCOPE_CALLBACKS = "viewScope.callbacks"; @Override public Object get(String name, ObjectFactory objectFactory) { Map viewMap = getViewMap(); Object instance = viewMap.get(name); if (instance == null) { instance = objectFactory.getObject(); synchronized (viewMap) { viewMap.put(name, instance); logger.debug("Bean '{}' has been put to ViewScope.", instance); } } else { logger.debug("Going to return an existing bean '{}'", instance); } return instance; } @Override public Object remove(String name) { Object instance = getViewMap().remove(name); if (instance != null) { Map callbacks = (Map) getViewMap().get(VIEW_SCOPE_CALLBACKS); if (callbacks != null) { callbacks.remove(name); logger.debug("Bean '{}' has been removed.", instance); } } return instance; } @Override public void registerDestructionCallback(String name, Runnable runnable) { Map callbacks = (Map) getViewMap().get(VIEW_SCOPE_CALLBACKS); if (callbacks != null) { callbacks.put(name, runnable); logger.debug("Registered callback for '{}'", name); } } /** * {@inheritDoc} */ @Override public Object resolveContextualObject(String name) { FacesContext facesContext = FacesContext.getCurrentInstance(); FacesRequestAttributes facesRequestAttributes = new FacesRequestAttributes(facesContext); return facesRequestAttributes.resolveReference(name); } @Override public String getConversationId() { FacesContext facesContext = FacesContext.getCurrentInstance(); FacesRequestAttributes facesRequestAttributes = new FacesRequestAttributes(facesContext); return facesRequestAttributes.getSessionId() + "-" + facesContext.getViewRoot().getViewId(); } private Map getViewMap() { return FacesContext.getCurrentInstance().getViewRoot().getViewMap(); } } 

我修复了这个问题,只是将@Transactional放在方法的顶部。

为了防止我的应用程序中出现LazyLoadingException ,我使用一个帮助器方法,首先将实体合并回会话,然后初始化请求的集合。 它最近发现,有时它仍然受到“收集与任何会话无关”的问题,尽管会议似乎是开放的,整体看起来很好。 我很难说出这种行为的原因是什么,但我仍然找到了对付它的补救措施。 尝试在使用session.refresh(entity)获取延迟集合之前刷新实体状态。 这将导致Hibernate从数据库重新加载您的实体。 执行此操作后,您当前的会话将允许您使用Hibernate.initialize()顺利加载您的集合。

正如@Zmicier Zaleznicenka指出的那样,此exception消息可能与Session无关。 我们也遇到过这个问题,但根本原因是映射文件中定义的实体主键设置不正确。 例如,在以下代码中,数据库列“Foo_SK”不是表的唯一标识符。

 Id(x => x.Id, "Foo_SK").GeneratedBy.Assigned(); 

在我们的例子中,我们无法控制数据库模式。 因此,我们使用复合键映射来修复问题。

有关同一问题,请查看其他post。

我也遇到过这个问题,但问题是我没有在配置文件中配置事务管理,所以:

@EnableTransactionManagement添加到java Config文件或将到xml配置文件

看起来你在AbstractIntegrationManagedBeaninit方法中调用它。

你必须确保在那之前正确设置了hibernate。

很可能你的配置没有反映出来,你认为hibernate已经存在,尽管不能保证。

有关更多详细信息,请参阅此问题: 如何在Spring中控制bean init-method调用的顺序?

我修复了这个问题,只是将@Transactional放在方法的顶部。 并且还通过它的id获取类:

 Test s=get(test.getId())