spring mvc(spring boot) 整合Mybatis且开启懒加载,直接返回对象就会出现
Could not write JSON: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.xfishtour.entity.result2.JsonResult[\"data\"]->java.util.ArrayList[0]->com.xxx.xxxx_$$_jvstc2b_0[\"handler\"])
除了关闭全局懒加载外,解决办法有3个
1.关闭该查询的懒加载 fetchType="eager"
<collection ... fetchType="eager"> </collection>
2.返回的类加上注解
@JsonIgnoreProperties(value = { "handler" })
3.配置json转换器属性SerializationFeature.FAIL_ON_EMPTY_BEANS为false
该方法从:https://blog.csdn.net/justinytsoft/article/details/53575236得知
以spring boot为例:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = new ObjectMapper();
//null字段不返回
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// mybatis 使用懒加载后,返回JSON报错
// 而且这个配置不能放在“null字段不返回”配置前面,否则"null字段不返回"配置会失效
// @see <a href="https://blog.csdn.net/justinytsoft/article/details/53575236"></a>
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jackson2HttpMessageConverter);
}
}
第3种方法应该是比较完美的了。但是返回前端的时候,对象会多出一个字段handler:"",反正不影响了。若是想去掉这个东西,第2、3种方法一起用即可