【轉】使用Mybatis時遇到的延遲加載造成返回異常的問題——HttpMessageConversionException: Type definition error


在使用Mybatis的過程中,使用了resultMap延遲加載。

延遲加載:association聯表查詢的過程中,查詢另外兩個表的對象。而延遲加載是指只有在使用這兩個對象的時候才會進行查詢。

問題的產生,在我這里,我是直接通過路由url直接查詢 StudentDto_2 對象。延遲加載的對象為 TClass 和 Assistant.

public class StudentDto_2 {
    private Integer stuId;
    private String stuNum;  //學生編號,unique
    private String studentName;
    private Long birthDate;
    private TClass tClass;
    private Assistant assistant;
}

在序列化的過程中,會拋出以下異常。

2018-08-27 11:14:29.339 ERROR 34755 --- [nio-8089-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 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.zimo.mybaties.util.Result["data"]->com.zimo.mybaties.dto.StudentDto_2_$$_jvstfe4_0["handler"])] with root cause

問題:Springmvc+mybatis,mybatis配置延遲加載時,json序列化異常

我目前的解決辦法是關閉延遲加載,關閉后一切正常。

尋找另外一種方法

參考鏈接:https://blog.csdn.net/justinytsoft/article/details/53575236

在SpringBoot中,默認使用Jackson來實現java對象到json格式的序列化與反序列化。Jackson的轉化是通過ObjectMapper來實現的。SpringBoot內置了一個ObjectMapper。我們通過下面的配置來

實現序列化Mybatis的延遲加載。

package com.zimo.mybaties.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomerMapper extends ObjectMapper {
    public CustomerMapper() {
        this.setSerializationInclusion(JsonInclude.Include.NON_NULL);  //返回為null的值則去除,
        this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);  //解決延遲加載的對象
    }
}

返回參數中了多了一個代理對象handle

{
"code": 200,
"message": "獲取學生信息",
-"data": {
    "stuId": 22,
    "stuNum": "12310",
    "studentName": "天涯10",
    "birthDate": 777524356000,
    -"tClass": {
        "classId": 3,
        "classNum": "1921083145",
       "className": "數學"
        },
    -"assistant": {
       "assistantId": 1,
        "assistantNum": "1315151521",
        "name": "還在於是"
        },
    "handler": { }
    }
}

轉自:https://www.cnblogs.com/wbq1113/p/9541114.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM