Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid lazy fetch in JSON serialization using Spring Data JPA + Spring Web MVC?

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?

like image 535
Ronye Vernaes Avatar asked Feb 26 '15 15:02

Ronye Vernaes


1 Answers

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

like image 95
Master Slave Avatar answered Oct 08 '22 10:10

Master Slave