【问题标题】:Spring Data Rest: Entity serialization with LAZY object cause JsonMappingExceptionSpring Data Rest:使用 LAZY 对象进行实体序列化导致 JsonMappingException
【发布时间】:2016-11-15 22:35:36
【问题描述】:

我在 Spring Data Rest 项目中遇到以下异常:

com.fasterxml.jackson.databind.JsonMappingException: 
    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) ) 
(through reference chain: org.springframework.data.rest.webmvc.json.["content"]->test.spring.data.rest.xml.entities.Author_$$_jvstb93_1["handler"])

当然,我有一些实体的 fetch 配置 = FetchType.LAZY。

我遵循了许多说明和链接,但我仍然有这个例外。

我已经尝试过的事情(没有效果):

  • 在扩展 RepositoryRestMvcConfiguration 的配置类中添加 @EnableHypermediaSupport(type = HypermediaType.HAL)

  • @Override configureJacksonObjectMapper 在同一个类中,同时使用Jackson2DatatypeHelper.configureObjectMapper():

    @Override
    protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        Jackson2DatatypeHelper.configureObjectMapper(objectMapper);
    }
    
  • 在 web.xml 中添加“org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter”过滤器

  • 使用此构造函数创建一个extends ObjectMapper 的自定义类:

    public HibernateAwareObjectMapper() {
        Hibernate5Module hm = new Hibernate5Module();
        registerModule(hm);
    }
    

    还有这个配置:

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="test.spring.data.rest.xml.config.HibernateAwareObjectMapper" />
            </property>
        </bean>
    </mvc:message-converters>
    

以上操作均未解决问题!

如何(肯定)解决这个问题?

谢谢。

【问题讨论】:

    标签: spring-mvc spring-data-jpa spring-data-rest


    【解决方案1】:

    我已经找到解决这个烦人问题的方法了。

    必须为 Spring Data Rest 应用程序的每个存储库定义一个自定义 @Projection;在投影中会有必需的字段。

    注意,如果两个实体之间存在循环引用,则投影的相关方法必须用@JsonBackReference注解(对于@ManyToOne注解的字段)和@JsonManagedReference注解(对于@OneToMany注解字段),否则在 JSON 序列化中会有一个 JSON 循环。

    在每个@Repository 注释(或@RepositoryRestResource 注释)中,必须使用自定义投影标记excerptProjection 属性。

    有了这样的管理,就不需要任何其他的配置,Lazy对象的异常终于消失了。

    【讨论】:

      猜你喜欢
      • 2018-04-17
      • 2016-09-25
      • 2016-05-05
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2017-07-04
      • 2014-11-12
      • 2013-01-04
      相关资源
      最近更新 更多