我在 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"])
当然,我有一些具有获取配置 = FetchType.LAZY 的实体。
我遵循了很多说明和链接,但仍然有这个异常(exception)。
我已经尝试过做的事情(没有效果):
在扩展 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
”过滤器使用以下构造函数创建一个
扩展 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 Data Rest 应用程序的每个存储库,都必须定义一个自定义的 @Projection
;投影中会有必要的字段。
注意,如果两个实体之间存在循环引用,则投影的对应方法必须使用@JsonBackReference
注解进行注解(对于@ManyToOne
注解的字段)并带有@JsonManagedReference
注解(针对@OneToMany
注解字段),否则JSON序列化中将会出现JSON循环。
在每个 @Repository
注释(或 @RepositoryRestResource
注释)中,必须使用自定义投影将其标记为 excerptProjection 属性。
通过这种管理,不需要任何其他配置,Lazy 对象的异常终于消失了。
关于spring-mvc - Spring 数据休息: Entity serialization with LAZY object cause JsonMappingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38349986/