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


问题内容

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

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

Entity <--> Repository <--> Service <--> Controller

在实体级别,我有@OneToMany字段,FetchType = LAZY。

当REST控制器进行序列化时,将进行提取,但这在某些情况下是不可取的。

我已经尝试使用@JSONInclude Jackson批注,并且序列化仍然发生。

有人可以为我提供可靠的解决方案吗?


问题答案:

如果我对您的理解正确,则只希望在获取延迟加载的集合时进行序列化,但是不希望序列化触发获取。

如果是这种情况,则应使用jackson-datatype-hibernate,并按其文档中的说明进行添加

public class HibernateAwareObjectMapper extends ObjectMapper {

    public HibernateAwareObjectMapper() {
        registerModule(new Hibernate4Module());
    }
}

比注册

 <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>

该模块具有 Feature.FORCE_LAZY_LOADING 设置,该设置指示是否应强制加载对象然后对其进行序列化,默认情况下该值设置为
false ,我相信这是您需要的行为