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

Service中的代码
Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatisPojo类
Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis
mybatis的映射文件
Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis

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

进行测试,结果如下
Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis
断点调试后,发现返回的实体类,多了个属性handler
Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis
再实体类上加上@JsonIgnoreProperties(value = “handler”)
Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis
测试结果
Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis
原因
在采用redis存数据时,mybatis采用懒加载的时候,会生成一个关联实体类代理对象,代理对象会生成一个handler属性,由于jackson序列化的时候,handler没有getter和setter方法,会报出异常,在关联的类上面加@JsonIgnoreProperties(value = “handler”),忽略此属性值,即可解决.

Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis
注意:redis存数据时,会先执行get去内存数据库拿数据,如果内存数据库没有,则执行sql语句,查到封装对象后,调用put方法,把数据存入redis中(懒加载会触发),之后再返回对象给Controller,因此,无论Controller类中,有没有触发mybatis的懒加载,懒加载的对象都会被查询出来

Mybatis懒加载,返回JSON异常 Could not write JSON: No serializer found for class org.apache.ibatis
存入redis中,是有两条数据,一条是key为com.atguigu.cache.mapper.DepartmentMapper.getEmBy的数据,一条是key为com.atguigu.cache.mapper.EmployeeMapper.getEmById的数据,因为连表查询,一共会调用两次put方法存数据,第一次是.DepartmentMapper触发的,之后会遍历DepartmentMapper.xml的关联表的方法,取出来作为key,再调用put方法,存储数据.