springboot 中 hibernate 与 jackson 混合使用报错
springboot的jpa,查询到一个对象后使用jackson对对象进行转换时,报了以下错误:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 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: com.example.demo.Girl_$$_jvstc9d_0["handler"])
原因:一开始以为该对象为空,但用syso打印该对象,每个属性都有值,并不存在空的属性。后来发现是 hibernate 懒加载机制造成的。
hibernate会给被管理的pojo加入 hibernateLazyInitializer 等属性。jackson通过java的反射机制将pojo转换成json,会把hibernateLazyInitializer也拿出来操作,但是hibernateLazyInitializer无法由反射得到,所以就抛异常了。
解决方法:在实体类上加以下注解
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler","fieldHandler" })
@Entity