mybitis懒加载Could not write JSON:No serializer...

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种方法一起用即可

转载于:https://my.oschina.net/yejunxi/blog/1836329

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值