1. 程式人生 > >Mybatis懶載入時,springMVC返回JSON異常 Could not write JSON: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$En

Mybatis懶載入時,springMVC返回JSON異常 Could not write JSON: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$En

在mybatis整合springmvc時,假如mybatis採用了懶載入,而springmvc中利用@ResponseBody註解返回實體類的JSON時會拋異常:

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);


先看出現問題的程式碼:

首先是controller中返回的是responsebody:

    /**
     * 根據訂單ID查詢訂單
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query/{orderId}" ,method = RequestMethod.GET)
    public Order queryOrderById(@PathVariable("orderId") String orderId) {
        return orderService.queryOrderById(orderId);
    }

 

service中的程式碼:

    public Order queryOrderById(String orderId) {
        Order order = orderDao.queryOrderById(orderId);
        return order;
    }
    public Order queryOrderById(String orderId) {
        return this.orderMapper.queryByID(orderId);
    }

呼叫的mapper.xml中使用了懶載入:

    <resultMap type="Order" id="pojoResultMap" autoMapping="true">
        <id column="order_id" property="orderId"/>
        <association property="orderShipping" javaType="OrderShipping" column="order_id" select="queryOrderShippingByOrderId" autoMapping="true" fetchType="lazy"></association>
        <collection property="orderItems" javaType="Arraylist" ofType="OrderItem" autoMapping="true" select="queryOrderItemByOrderId" column="order_id" fetchType="lazy">
        </collection>
    </resultMap>

這個時候測試就會上面的異常.

經過除錯後發現,原來service中執行過queryByID的方法後,返回的實體類Order被做了代理,如下:

可以看到,被代理後的Order類多了一個handler的屬性,之後Jackson在對該代理類做序列化時,由於找不到對應的getter,異常就丟擲來辣!

解決方法:

在被代理的Order類上加上 @JsonIgnoreProperties(value = "handler") 註解,讓Jackson序列化時忽略handler屬性:

 

 

 問題解決!