Reputation: 2061
I'm trying to serialize an object with several lazily loaded properties, and I'm getting the following error:
Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
After some searching I have tried this in my @Configuration class, but it doesn't seem to help:
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
Hibernate4Module hibernateModule = new Hibernate4Module();
hibernateModule.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, false);
objectMapper.registerModule(hibernateModule);
return objectMapper;
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
return converter;
}
When I change to FetchType.EAGER the application works fine.
Upvotes: 0
Views: 1382
Reputation: 6944
The problem is related to the fact that related objects to the main one are not really loaded when you execute the query and not use the FetchType.EAGER; by using the FetchType.EAGER you tell hibernate: load the main entity and all the related entities; this can have not too much sense (you can risk to load all the database in one query) Returning to jackson marshaller, when objects are "proxied" it is not able in serializing them IMHO i'd do the following: i'd create a DTO object to be serialized (I'd not serialize the Hibernate object) i'd put in this DTO only the needed properties and data if user need to see related objects a specific call would be executed and data related to the selected object will be loaded from DB and serialized (in specific DTO objects)
Upvotes: 1