Skip to main content

How to Send Rest Response For Lazy fetched Hibernate Objects with Jackson

How to Send Rest Response For Lazy fetched Hibernate Objects with Jackson

Just add the following class to your application and your jackson will be configured to send the JSON response for the LAZY fetched domain objects.

You need to add the dependency  compile("com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:2.6.1")

@Configuration
@EnableWebMvc
public class HibernateAwareObjectMapper extends WebMvcConfigurerAdapter {

//More configuration....

/* Here we register the Hibernate4Module into an ObjectMapper, then set this custom-configured ObjectMapper
* to the MessageConverter and return it to be added to the HttpMessageConverters of our application*/
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);
}

//More configuration....

}

With this class in class path you will be able to send the rest response for the LAZY fetched Hibernate Entities. 

Comments