If you are using SpringBoot, ideally you should already have a Hibernate4Module . Otherwise add this dependency
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-hibernate4</artifactId> <version>2.5.3</version> </dependency>
Then create a class called "HibernateAwareObjectMapper" or whatever you call:
with the 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 HibernateAwareObjectMapper through the message converter. To do this, create a Config class that extends the WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter extension. (If you already have one, just follow the next step).
Now register MessageConverter with HibernateObjectMapper:
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters){ List<MediaType> 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) method for this spring web application.
Do not forget to comment if you want to add an answer.
RK Punjal
source share