In spring boot mvc project with pure java configuration how to configure Jackson to omit lazy load Attributes
If you are using SpringBoot, ideally you should already have Hibernate4Module. Else add this dependency
com.fasterxml.jackson.datatype
jackson-datatype-hibernate4
2.5.3
Next create a class called "HibernateAwareObjectMapper" or whatever you want to name it:
with following contents:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
public class HibernateAwareObjectMapper extends ObjectMapper {
public HibernateAwareObjectMapper() {
registerModule(new Hibernate4Module());
}
}
for different versions of Hibernate, refer to these Hibernate modules:
// for Hibernate 4.x:
mapper.registerModule(new Hibernate4Module());
// or, for Hibernate 5.x
mapper.registerModule(new Hibernate5Module());
// or, for Hibernate 3.6
mapper.registerModule(new Hibernate3Module());
Now you need to register your HibernateAwareObjectMapper through a message Converter. For this create a Config class that extens extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter. (If you already have one just follow the next step).
Now register the MessageConverter using HibernateObjectMapper :
@Override
public void configureMessageConverters(List> converters){
List supportedMediaTypes=new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
MappingJackson2HttpMessageConverter converter=new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new HibernateAwareObjectMapper());
converter.setPrettyPrint(true);
converter.setSupportedMediaTypes(supportedMediaTypes);
converters.add(converter);
super.configureMessageConverters(converters);
}
Viola !!! That should be enough. This is the pure-java (no-xml) way of doing this for a spring boot web app.
Feel free to comment if you want to add to Answer.