I have a solution using Spring Data JPA and a REST Controller in Spring Web MVC. The persistence provider is Hibernate.
The persistence layer is built using Spring Repositories and between de REST Controller and the repository exists a Service Layer:
Entity <--> Repository <--> Service <--> Controller
At entity level, I have @OneToMany fields with FetchType = LAZY.
When the REST Controller make the serialization, the fetching is made, but this is undesirable in some cases.
I already tried with @JSONInclude Jackson annotation and the serialization still occurs.
Can somebody help me with a proved solution?
If I understood you properly, you want to serialize only when the lazy loaded collection is fetched, but you don't want the serialization to trigger the fetching.
If that is the case you should use the jackson-datatype-hibernate, and added as their docs already explains
public class HibernateAwareObjectMapper extends ObjectMapper {
public HibernateAwareObjectMapper() {
registerModule(new Hibernate4Module());
}
}
than register
<mvc:annotation-driven>
<mvc:message-converters>
<!-- Use the HibernateAware mapper instead of the default -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="path.to.your.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
The module has a Feature.FORCE_LAZY_LOADING settings, that tells whether the object should be forced to be loaded and then serialized, which is by default set to false which I believe is the behaviour you need
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With