JsonMappingException: could not initialize proxy - no Session

后端 未结 4 1286
小鲜肉
小鲜肉 2020-12-03 02:01

I am building a RESTful Web Service that consumes and returns JSON. I am encountering the following stack trace when I try to fetch an ESRBRating object from the database th

相关标签:
4条回答
  • 2020-12-03 02:20

    @JsonIgnore annotation might solve your problem, but it causes that particular field that you initially set as FetchType.LAZY to be completely ignored. A better alternative is given here https://stackoverflow.com/a/21760361/3609067

    0 讨论(0)
  • 2020-12-03 02:22

    This typically happens when you are returning an object via @Responsebody (or in your case response body by way of @RestController) and an object is being serialized but has children in a LAZY collection that have not been referenced. By the time you are in your controller there is no longer a transaction active that will facilitate them being fetched (like the one your started in your @Service). You can either make your fetch strategy EAGER, bring in your collections by reference while still in your transaction or make your LAZY collections JSON Transient.

    0 讨论(0)
  • 2020-12-03 02:40

    First download jackson-datatype-hibernate4-2.2.3.jar or higher version according to jackson-core version. Then use this code in config file and you can use fetch strategy LAZY without any error.

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
    
    
    public class ApplicationConfig extends WebMvcConfigurerAdapter
    {
    public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
        MappingJackson2HttpMessageConverter messageConverter = new  MappingJackson2HttpMessageConverter();
    
        ObjectMapper mapper = new ObjectMapper();
        //Registering Hibernate4Module to support lazy objects
        mapper.registerModule(new Hibernate4Module());
    
        messageConverter.setObjectMapper(mapper);
        return messageConverter;
    
    }
    
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //Here we add our custom-configured HttpMessageConverter
        converters.add(jacksonMessageConverter());
        super.configureMessageConverters(converters);
    }
    
    0 讨论(0)
  • 2020-12-03 02:46

    Solved for Spring Boot 2.3.0 by adding to gradle.build:

    implementation 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:2.11.3'

    And declaring one more bean:

    @Bean
    public Module datatypeHibernateModule() {
        return new Hibernate5Module();
    }
    
    0 讨论(0)
提交回复
热议问题