Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

HTTP Status 500: failed to lazily initialize

Estou chamando a URL: http://localhost:8080/minhalivraria/livro/2 para obter o livro de id=2 em formato JSON porém o erro abaixo aparece no navegador e não aparece no console. No método que mapeia essa URL eu fiz um println e o produto aparece normal, com todos os dados. Oque será que pode esta causando esse erro:

GitHub: https://github.com/CarlosEReis/MinhaLivraria

Erro no "navegador":

HTTP Status 500 - Could not write content: failed to lazily initialize a collection of role: br.com.carlosreis.minhaloja.models.Autor.livros, could not initialize proxy - no Session (through reference chain: br.com.carlosreis.minhaloja.models.Livro["autor"]->br.com.carlosreis.minhaloja.models.Autor["livros"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: br.com.carlosreis.minhaloja.models.Autor.livros, could not initialize proxy - no Session (through reference chain: br.com.carlosreis.minhaloja.models.Livro["autor"]->br.com.carlosreis.minhaloja.models.Autor["livros"])

type Exception report

message Could not write content: failed to lazily initialize a collection of role: br.com.carlosreis.minhaloja.models.Autor.livros, could not initialize proxy - no Session (through reference chain: br.com.carlosreis.minhaloja.models.Livro["autor"]->br.com.carlosreis.minhaloja.models.Autor["livros"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: br.com.carlosreis.minhaloja.models.Autor.livros, could not initialize proxy - no Session (through reference chain: br.com.carlosreis.minhaloja.models.Livro["autor"]->br.com.carlosreis.minhaloja.models.Autor["livros"])

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: failed to lazily initialize a collection of role: br.com.carlosreis.minhaloja.models.Autor.livros, could not initialize proxy - no Session (through reference chain: br.com.carlosreis.minhaloja.models.Livro["autor"]->br.com.carlosreis.minhaloja.models.Autor["livros"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: br.com.carlosreis.minhaloja.models.Autor.livros, could not initialize proxy - no Session (through reference chain: br.com.carlosreis.minhaloja.models.Livro["autor"]->br.com.carlosreis.minhaloja.models.Autor["livros"])
    org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:273)
    org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:225)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:173)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:130)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: br.com.carlosreis.minhaloja.models.Autor.livros, could not initialize proxy - no Session (through reference chain: br.com.carlosreis.minhaloja.models.Livro["autor"]->br.com.carlosreis.minhaloja.models.Autor["livros"])
    com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:210)
    com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:177)
    com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:199)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:683)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:656)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:675)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
    com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:130)
    com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1387)
    com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:889)
    org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:266)
    org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:225)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:173)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:130)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: br.com.carlosreis.minhaloja.models.Autor.livros, could not initialize proxy - no Session
    org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:572)
    org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:212)
    org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:153)
    org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:278)
    com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:101)
    com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:24)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:656)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:675)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
    com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:656)
    com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:675)
    com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
    com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:130)
    com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1387)
    com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:889)
    org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:266)
    org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:225)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:173)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:130)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

note The full stack trace of the root cause is available in the Apache Tomcat/8.5.11 logs.
Apache Tomcat/8.5.11

Método controller:

    @GetMapping("/{id}")
    @ResponseBody
    public Livro livroJson(@PathVariable("id") Long id) {
        Livro livro = livroDao.findBy(id);
        System.out.println(livro);
        return livro;
    }

Console:

Hibernate: select distinct livro0_.id as id1_1_0_, autor1_.id as id1_0_1_, livro0_.autor_id as autor_i10_1_0_, livro0_.conteudo as conteudo2_1_0_, livro0_.dataLancamento as dataLanc3_1_0_, livro0_.isbn as isbn4_1_0_, livro0_.pathCapa as pathCapa5_1_0_, livro0_.qtdePaginas as qtdePagi6_1_0_, livro0_.subTitulo as subTitul7_1_0_, livro0_.sumario as sumario8_1_0_, livro0_.titulo as titulo9_1_0_, precos2_.Livro_id as Livro_id1_1_0__, precos2_.tipo as tipo2_2_0__, precos2_.valor as valor3_2_0__, autor1_.descricao as descrica2_0_1_, autor1_.nome as nome3_0_1_, autor1_.pathFoto as pathFoto4_0_1_, precos2_.Livro_id as Livro_id1_1_0__, precos2_.tipo as tipo2_2_0__, precos2_.valor as valor3_2_0__ from Livro livro0_ inner join Autor autor1_ on livro0_.autor_id=autor1_.id inner join Livro_precos precos2_ on livro0_.id=precos2_.Livro_id where livro0_.id=?
Livro [id=2, 
titulo=Algoritmos em Java, 
subTitulo=Busca, ordenação e análise, 
conteudo=Em nosso dia a dia, realizamos uma série de buscas e ordenações que nos são tão naturais, 
autor=
Autor [id=1, nome=Carlos Reis], 
qtdePaginas=223, 
dataLancamento=java.util.GregorianCalendar[time=1503284400000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Sao_Paulo",offset=-10800000,dstSavings=3600000,useDaylight=true,transitions=129,lastRule=java.util.SimpleTimeZone[id=America/Sao_Paulo,offset=-10800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=9,startDay=15,startDayOfWeek=1,startTime=0,startTimeMode=0,endMode=3,endMonth=1,endDay=15,endDayOfWeek=1,endTime=0,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=7,WEEK_OF_YEAR=34,WEEK_OF_MONTH=4,DAY_OF_MONTH=21,DAY_OF_YEAR=233,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=-10800000,DST_OFFSET=0], 
isbn=978-85-5519-243-2, 
precos=[
Preco [valor=29.00, tipo=IMPRESSO], 
Preco [valor=69.00, tipo=EBOOK], 
Preco [valor=79.00, tipo=COMBO]]]
1 resposta
solução!

Removi uma list de livros da minha classe autor que fazia um relacionamento bidirecional com a classe livro, e voltou ao normal.