Avoid Jackson Serialization on Non-Fetched Lazy Objects
When lazy-fetched Hibernate objects are serialized using Jackson, a JsonMappingException can be thrown due to the lack of initialization. To resolve this issue, several approaches can be implemented.
One method is to register the Hibernate4Module with the default MappingJackson2HttpMessageConverter provided by Spring. This can be achieved by extending the Spring configuration class (WebMvcConfigurerAdapter) and overriding the configureMessageConverters method. Within this method, a new MappingJackson2HttpMessageConverter should be created and customized with the Hibernate4Module. This converter can then be added to the HttpMessageConverters of the application.
For XML configuration, instead of creating a custom HttpMessageConverter, a HibernateAwareObjectMapper must be created. This mapper can then be set as the objectMapper property of the MappingJackson2HttpMessageConverter. Subsequently, MappingJackson2HttpMessageConverter should be added as a message-converter in the XML configuration.
By implementing one of these approaches, Jackson will be prevented from attempting to serialize unfetched lazy objects, resolving the JsonMappingException and ensuring proper serialization.
The above is the detailed content of How to Prevent Jackson Serialization Errors with Hibernate Lazy-Loaded Objects?. For more information, please follow other related articles on the PHP Chinese website!