Home >Java >javaTutorial >How to Prevent Jackson from Serializing Lazy-Fetched Hibernate Objects?
Avoid Jackson Serialization on Lazy Fetched Objects
This article addresses the challenge of preventing Jackson from serializing unfetched, lazy-loaded objects, which can result in Hibernate-related exceptions.
Introduction
In the provided scenario, a User object with a lazy-fetched coordinates list results in a "could not initialize proxy - no Session" exception when Jackson attempts to serialize the object. This is because Jackson eagerly fetches the coordinates before serialization, violating the lazy loading mechanism.
Solution
The solution involves integrating a custom mapping converter that incorporates the Hibernate4Module. This module enhances Jackson's support for lazy-loaded objects.
Spring Java Configuration
@Configuration @EnableWebMvc public class MyConfigClass extends WebMvcConfigurerAdapter{ public MappingJackson2HttpMessageConverter jacksonMessageConverter(){ MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new Hibernate4Module()); messageConverter.setObjectMapper(mapper); return messageConverter; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(jacksonMessageConverter()); super.configureMessageConverters(converters); } }
public @ResponseBody User getUser(@PathVariable String username) { User user = userService.getUser(username); return user; }
Spring XML Configuration
<bean class="com.pastelstudios.json.HibernateAwareObjectMapper">
<mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper" ref="hibernateAwareObjectMapper" /> </bean> </mvc:message-converters>
By implementing this solution, Jackson is prevented from eagerly fetching unfetched lazy objects during serialization, resolving the exception and preserving the lazy loading behavior.
The above is the detailed content of How to Prevent Jackson from Serializing Lazy-Fetched Hibernate Objects?. For more information, please follow other related articles on the PHP Chinese website!