JsonMappingException: could not initialize proxy - no Session
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);
}
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.