Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.

问题描述

最近在开发项目的时候,遇到这个问题.

Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl

以下是异常堆栈打印信息:
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.
在信息中,我们看到问题出在 org.zlc.shoppingmall.po.Order_$$_jvst986_0["handler"]处,Order对象被代理了,并且多了个handler属性,该属性是org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl 的类.
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.
动态代理生成的类是在运行时生成的,jackson在序列化的时候找不到对应的类的元数据,因此无法进行序列化,且因jackson的默认配置是SerializationFeature.FAIL_ON_EMPTY_BEANS,所以在找不到bean对应的访问类型时报错.
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.

解决办法

知道了错误原因,解决起来就很简单了.

1.在被代理的类上添加注解

@JsonIgnoreProperties(value = {“handler”})
添加了该注解之后,Jackson就会忽略该字段的序列化和反序列化了.
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.

2.修改Jackson的配置

Jackson报错是因为默认配置FAIL_ON_EMPTY_BEANS为true,导致的不能序列化异常的抛出,因此可以修改对应配置项,让Jackson不抛出该异常.
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.

3.修改MyBatis的加载模式为FetchType.EAGER

FetchType.LAZY 修改为FetchType.EAGER. 因为 FetchType.LAZY会被MyBatis创建动态代理类.
Mybatis懒加载时,springMVC返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis.

其他方法或许还有.