本文介绍了无法取得LAZY - JPA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想在JPA的OneToMany关系中执行LAZY加载。 问题是,当我想要访问LAZY加载的属性时,我得到一个异常。我知道在尝试访问属性时我必须处于事务中。但似乎交易没有开放。这是个例外: org.hibernate.LazyInitializationException:无法懒惰地初始化一个角色集合:de.recipemanager.recipe。 data.Recipe.ingredients,无法初始化代理 - 在org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)无会话 在org.hibernate.collection.internal.AbstractPersistentCollection在org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545).withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186) 在org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection .java:124) at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266) at de.recipemanager.recipe.web.IngredientDTOList。< init>(IngredientDTOList。 java:27) at de。 < init>(RecipeDTO.java:28) at de.recipemanager.recipe.web.RecipeDTOServiceImpl.get(RecipeDTOServiceImpl.java:22) at de.recipemanager .recipe.web.RecipeController.get(RecipeController.java:32) 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.web .method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)在org.springframework.web .servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter。 at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet。 at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) at org .springframework.web.servlet.FrameworkServlet.servi ce(FrameworkServlet.java:812) at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java: 594)在org.eclipse.jetty.servlet.ServletHandler $ CachedChain.doFilter(ServletHandler.java:1366)在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java: 330),位于org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) 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)在org.springframework.security.web.FilterChain代理$ VirtualFilterChain.doFilter(FilterChainProxy.java:342)在org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)在org.springframework.security.web。的FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)处org.springframework.security.web org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)。的FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)处org.springframework.security.web org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:150)。 FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) at org.sp ringframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:201) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)。在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)在org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)。在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)在org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)。在org.springframew ork.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)$ or $ at org.eclipse.jetty.servlet.ServletHandler $ CachedChain.doFilter(ServletHandler.java:1337) at org.eclipse.jetty.servlet。 ServletHandler.doHandle(ServletHandler.java:484)位于org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)位于org.eclipse.jetty.security.SecurityHandler。处理(SecurityHandler.java:524)在org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)在org.eclipse.jetty.server.handler.ContextHandler。 doHandle(ContextHandler.java:1065)在org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:413)在org.eclipse.jetty.se rver.session.SessionHandler.doScope(SessionHandler.java:192)$ or $。 org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999) at org.eclipse.jetty。 server.handler.ScopedHandler.handle(ScopedHandler.java:117)在org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)在org.eclipse.jetty。 server.handler.HandlerCollection.handle(HandlerCollection.java:149)$ or $。 org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111) at org.eclipse.jetty。 server.Server.handle(Server.java:351)在org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454) at org.eclipse.jetty.server.AbstractHttpConnection。 headerComplete(AbstractHttpConnection.java:890) at org.eclipse.jetty.server.AbstractHttpConnection $ RequestHandler.headerComplete(AbstractHttpConnection.java:944) org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:634) at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230) at org.eclipse .jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:77) at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:609) at org.eclipse.jetty .io.nio.SelectChannelEndPoint $ 1.run(SelectChannelEndPoint.java:45)在org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:599)在org.eclipse。 jetty.util.thread.QueuedThreadPool $ 3.run(QueuedThreadPool.java:534)$ b $在java.lang.Thread.run(Thread.java:724) 2013-10-10 21:17:53.427 :警告:oejs.ServletHandler:/ api / recipes / 1 org.hibernate.LazyInitializationException:无法懒惰地初始化一个角色集合:de.recipemanager.recipe.data.Recipe.ingredients,无法初始化代理 - no会话在org.hibernate.collection.in在org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)处在org.hibernate.collection.internal.AbstractPersistentCollection处。初始化(AbstractPersistentCollection.java:545)在org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)在org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag。 java:266) at de.recipemanager.recipe.web.IngredientDTOList。< init>(IngredientDTOList.java:27) at de.recipemanager.recipe.web.RecipeDTO。< init>( RecipeDTO.java:28) at de.recipemanager.recipe.web.RecipeDTOServiceImpl.get(RecipeDTOServiceImpl.java:22) at de.recipemanager.recipe.web.RecipeController.get(RecipeController.java: 32)$ su n.reflect.NativeMethodAccessorImpl.invoke0(本机方法)在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)$在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)b $ b。在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal (RequestM appingHandlerAdapter.java:686)在org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)在org.springframework.web.servlet.DispatcherServlet.doDispatch( DispatcherServlet.java:925)在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856 )在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java: at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)在javax.servlet.http.HttpServlet.service(HttpServlet.java:848)在org.eclipse.jetty .servlet.ServletHolder.handle(ServletHolder.java:594) at org.eclipse.jetty.servlet.ServletHandler $ CachedChain.doFilter(Ser vletHandler.java:1366)处org.springframework.security.web.access.intercept.FilterSecurityInterceptor org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)。调用(FilterSecurityInterceptor.java:118)在org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)。在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)在org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)。在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.doFil之三(FilterChainProxy.java:342)处org.springframework.security.web.FilterChainProxy $ VirtualFilterChain org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)。 doFilter(FilterChainProxy.java:342) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:150) 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.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:201) at org.springframework.s ecurity.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)在org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)。在组织。 springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)处org.springframework org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)。 security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)在org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)在org.springframework.web.filter。 DelegatingFilterProxy.doFilter(DelegatingF在org.eclipse.jetty.servlet.ServletHandler上 $ C $ 在org.eclipse.jetty.servlet.ServletHandler.doHandle($ ServletHandler。 at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java: 524) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:524)$ or $ at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233) at org.eclipse.jetty.server.handler.ContextHandler.doHandle在org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)上 $ or $ 在org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:413) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)在org.ecl上 ipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149) at org。 eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111)$ or $。$ b $在org.eclipse.jetty.server.Server.handle(Server.java:351)在org.eclipse。 jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454)$ or $。 org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:890) at org.eclipse.jetty.server。 AbstractHttpConnection $ RequestHandler.headerComplete(AbstractHttpConnection.java:944) at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:634) at org.eclipse.jetty.http.HttpParser。 parseAvailable(HttpParser.java:230) at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:77) at org.ecl ipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:609) at org.eclipse.jetty.io.nio.SelectChannelEndPoint $ 1.run(SelectChannelEndPoint.java:45) at org .eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:599) at org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run(QueuedThreadPool.java:534) at java.lang.Thread.run(Thread.java:724) 实体: @Entity(name =recipe) public class Recipe { @Id @GeneratedValue 私人长ID; 私人字符串名称; 私有整数持续时间; @Enumerated(EnumType.STRING) private难度难度; @OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,orphanRemoval = true,mappedBy =recipe) List< Ingredient>配料; 抛出异常的代码: @Service @Transactional public class RecipeServiceImpl实现RecipeService { private final RecipeRepository recipeRepository; @Autowired public RecipeServiceImpl(RecipeRepository recipeRepository){ this.recipeRepository = recipeRepository; } @Override public Recipe get(Long id){ Recipe recipe = recipeRepository.findOne(id); if(recipe == null){ throw new EntityNotFoundException(配方ID:+ id +未找到。); } recipe.getIngredients(); 返回食谱; } 以及我的Spring配置: @Configuration @ComponentScan(basePackages =de.recipemanager) @EnableWebMvc public class ApplicationContext {} @Configuration @PropertySource(classpath:application.properties) @EnableJpaRepositories(basePackages =de.recipemanager) @EnableTransactionManagement public class JPAContext { private static final String PROPERTY_NAME_DATABASE_DRIVER =db.driver; private static final String PROPERTY_NAME_DATABASE_URL =db.url; private static final String PROPERTY_NAME_DATABASE_USERNAME =db.username; private static final String PROPERTY_NAME_DATABASE_PASSWORD =db.password; private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN =entitymanager.packages.to.scan; private static final String PROPERTY_NAME_HIBERNATE_DIALECT =hibernate.dialect; private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL =hibernate.format_sql; private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY =hibernate.ejb.naming_strategy; private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL =hibernate.show_sql; private static final String PROPERTY_NAME_HIBERNATE_AUTO =hibernate.hbm2ddl.auto; @资源私人环境环境; @Bean public DataSource dataSource()抛出PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER)); dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL)); dataSource.setUser(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME)); dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD)); 返回dataSource; $ b $Be public LocalContainerEntityManagerFactoryBean entityManagerFactory()抛出ClassNotFoundException,PropertyVetoException { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPackagesToScan( environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN)); entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class); 属性jpaProperties = new Properties(); jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT,environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT)); jpaProperties.put(PROPERTY_NAME_HIBERNATE_AUTO,environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_AUTO)); jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL,environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL)); jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY,environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY)); jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL,environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL)); entityManagerFactoryBean.setJpaProperties(jpaProperties); 返回entityManagerFactoryBean; $ b @Bean public JpaTransactionManager transactionManager()抛出ClassNotFoundException,PropertyVetoException { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory()。getObject()); 返回transactionManager; } } 我希望有人可以帮助我解决问题的解决方案,并对我的英语不好。 解决方案 我可以通过调用Materialslist的size()属性来实现它。 @Service @Transactional 公共类RecipeServiceImpl实现RecipeService { private final RecipeRepository recipeRepository; @Autowired public RecipeServiceImpl(RecipeRepository recipeRepository){ this.recipeRepository = recipeRepository; } @Override public Recipe get(Long id){ Recipe recipe = recipeRepository.findOne(id); if(recipe == null){ throw new EntityNotFoundException(配方ID:+ id +未找到。); } recipe.getIngredients()。size(); //需要在公开交易中获取配料。 返回食谱; 解决方案 c $ c> @Transactional method @Override public Recipe get ){食谱recipe = recipeRepository.findOne(id); if(recipe == null){ throw new EntityNotFoundException(配方ID:+ id +未找到。); } recipe.getIngredients(); 返回食谱; TransactionManager 提交/回滚事务并关闭会话。因此,对于任何延迟加载的实体,所连接的 Session 对象要么是 null ,要么是关闭的。那些实体不能被加载,并且hibernate会抛出一个异常。您需要将更广泛的 Session 作用域,可能带有 OpenSessionInViewFilter ,急切地加载实体,或者强制一些在 @Transactional 方法中,它们的初始化(您需要的那些)的初始化。 I want to do LAZY loading in a OneToMany Relation in JPA.The Problem is, that when i want to acces the LAZY loaded Attribute i get a exception. I know that i have to be in a Transaction when trying to access the attribute. But it seems like the Transaction is not open. This is the exception:org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: de.recipemanager.recipe.data.Recipe.ingredients, could not initialize proxy - no Session at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566) at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186) at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124) at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266) at de.recipemanager.recipe.web.IngredientDTOList.<init>(IngredientDTOList.java:27) at de.recipemanager.recipe.web.RecipeDTO.<init>(RecipeDTO.java:28) at de.recipemanager.recipe.web.RecipeDTOServiceImpl.get(RecipeDTOServiceImpl.java:22) at de.recipemanager.recipe.web.RecipeController.get(RecipeController.java:32) 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.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:594) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1366) 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: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:150) 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.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:201) 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.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.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:484) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:413) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117) at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111) at org.eclipse.jetty.server.Server.handle(Server.java:351) at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454) at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:890) at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:944) at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:634) at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230) at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:77) at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:609) at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:45) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:599) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:534) at java.lang.Thread.run(Thread.java:724)2013-10-10 21:17:53.427:WARN:oejs.ServletHandler:/api/recipes/1org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: de.recipemanager.recipe.data.Recipe.ingredients, could not initialize proxy - no Session at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566) at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186) at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124) at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266) at de.recipemanager.recipe.web.IngredientDTOList.<init>(IngredientDTOList.java:27) at de.recipemanager.recipe.web.RecipeDTO.<init>(RecipeDTO.java:28) at de.recipemanager.recipe.web.RecipeDTOServiceImpl.get(RecipeDTOServiceImpl.java:22) at de.recipemanager.recipe.web.RecipeController.get(RecipeController.java:32) 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.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:594) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1366) 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: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:150) 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.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:201) 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.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.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1337) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:484) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:413) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117) at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111) at org.eclipse.jetty.server.Server.handle(Server.java:351) at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454) at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:890) at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:944) at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:634) at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230) at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:77) at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:609) at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:45) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:599) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:534) at java.lang.Thread.run(Thread.java:724)The Entity: @Entity(name = "recipe")public class Recipe {@Id@GeneratedValueprivate Long id;private String name;private Integer duration;@Enumerated(EnumType.STRING)private Difficulty difficulty;@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "recipe")List<Ingredient> ingredients;The code where the exception is thrown:@Service@Transactionalpublic class RecipeServiceImpl implements RecipeService {private final RecipeRepository recipeRepository;@Autowiredpublic RecipeServiceImpl(RecipeRepository recipeRepository) { this.recipeRepository = recipeRepository;}@Overridepublic Recipe get(Long id) { Recipe recipe = recipeRepository.findOne(id); if(recipe == null) { throw new EntityNotFoundException("Recipe with id: " + id + " was not found."); } recipe.getIngredients(); return recipe;}And my Spring config:@Configuration@ComponentScan(basePackages = "de.recipemanager")@EnableWebMvcpublic class ApplicationContext {}@Configuration@PropertySource("classpath:application.properties")@EnableJpaRepositories(basePackages = "de.recipemanager")@EnableTransactionManagementpublic class JPAContext { private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver"; private static final String PROPERTY_NAME_DATABASE_URL = "db.url"; private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username"; private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password"; private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan"; private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect"; private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql"; private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy"; private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql"; private static final String PROPERTY_NAME_HIBERNATE_AUTO = "hibernate.hbm2ddl.auto"; @Resource private Environment environment; @Bean public DataSource dataSource() throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER)); dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL)); dataSource.setUser(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME)); dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD)); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException, PropertyVetoException { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPackagesToScan( environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN)); entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class); Properties jpaProperties = new Properties(); jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT)); jpaProperties.put(PROPERTY_NAME_HIBERNATE_AUTO, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_AUTO)); jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL)); jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY)); jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL)); entityManagerFactoryBean.setJpaProperties(jpaProperties); return entityManagerFactoryBean; } @Bean public JpaTransactionManager transactionManager() throws ClassNotFoundException, PropertyVetoException { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; }}I hope someone can help my figure out the solution for my problem, and sorry for my bad english.SolutionI could get it work by calling the size() attribute of the Ingredientslist.@Service@Transactionalpublic class RecipeServiceImpl implements RecipeService { private final RecipeRepository recipeRepository; @Autowired public RecipeServiceImpl(RecipeRepository recipeRepository) { this.recipeRepository = recipeRepository; } @Override public Recipe get(Long id) { Recipe recipe = recipeRepository.findOne(id); if(recipe == null) { throw new EntityNotFoundException("Recipe with id: " + id + " was not found."); } recipe.getIngredients().size(); //Needed to fetch the Ingredients in the open Transaction. return recipe; } 解决方案 Once you leave this @Transactional method@Overridepublic Recipe get(Long id) { Recipe recipe = recipeRepository.findOne(id); if(recipe == null) { throw new EntityNotFoundException("Recipe with id: " + id + " was not found."); } recipe.getIngredients(); return recipe;}The TransactionManager commits/rollsback the transaction and closes the session. As such, for any entities that were lazy loaded, the Session object that was attached is either null or is closed. Those entities cannot therefore be loaded and hibernate throws an Exception. You will need to either put a broader Session scope, possibly with an OpenSessionInViewFilter, eagerly load your entities, or force some of their initializations (the ones you need) inside the @Transactional method. 这篇关于无法取得LAZY - JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-18 12:24