如何使用Spring Data JPA + Spring Web MVC避免在JSON序列化中进行延迟提取?

Ron*_*aes 4 spring hibernate jpa spring-mvc spring-data

我在Spring Web MVC中使用Spring Data JPA和REST Controller有一个解决方案.持久性提供程序是Hibernate.

持久层是使用Spring Repositories构建的,在de REST Controller和存储库之间存在一个服务层:

Entity <--> Repository <--> Service <--> Controller
Run Code Online (Sandbox Code Playgroud)

在实体级别,我有@OneToMany字段,其中FetchType = LAZY.

当REST控制器进行序列化时,会进行提取,但在某些情况下这是不合需要的.

我已经尝试使用@JSONInclude Jackson注释,序列化仍然存在.

有人可以用经证实的解决方案帮助我吗?

Mas*_*ave 6

如果我理解正确,您只想在获取延迟加载的集合时序列化,但您不希望序列化触发提取.

如果是这种情况,你应该使用jackson-datatype-hibernate,并添加,因为他们的文档已经解释过

public class HibernateAwareObjectMapper extends ObjectMapper {

    public HibernateAwareObjectMapper() {
        registerModule(new Hibernate4Module());
    }
}
Run Code Online (Sandbox Code Playgroud)

比登记

 <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>
Run Code Online (Sandbox Code Playgroud)

该模块有一个Feature.FORCE_LAZY_LOADING设置,它告诉对象是否应该被强制加载然后序列化,默认情况下设置为false,我认为这是你需要的行为