在mybatis集成springmvc时,假如mybatis采用了懒加载,而在控制器中把返回的数据序列化成Json格式字符串,则会抛出异常:
There was an unexpected error (type=Internal Server Error, status=500).
Could not write JSON: No serializer found for class org.apache.ibatis.reflection.factory.DefaultObjectFactory and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
原因是MyBites代理的实体对象被代理后的类多了一个handler的属性,之后Jackson在对该代理类做序列化时,由于找不到对应的getter,异常就抛出来辣!
解决方法:
一、在被代理的类上加上 @JsonIgnoreProperties(value = "handler") 注解,让Jackson序列化时忽略handler属性,如:
/**
* 实体类,为了使用二级缓存,实现接口 Serializable
* @author Administrator
*/
@JsonIgnoreProperties(value= {"handler"})
public class Student implements Serializable {
/*
* 属性
*/
private int studentNo;
private Integer age;
private String name;
// get,set 封装方法省略
}
二、在MyBites的映射文件中把懒加载改成即时加载 fetchType="eager" ,默认值是 "lazy":
<resultMap type="Student" id="studentMap">
<association property="grade" column="gradeId"
select="com.bdqn.dao.GradeDao.findById" fetchType="eager"></association>
</resultMap>