Mybatis懶加載導致Json序列化問題
問題現場:
使用Mybatis, <collection> 標籤, 查一個實體類,和其子List. 報錯
[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.shuidihuzhu.cs.client.dto.ResponseDto["data"]->com.shuidihuzhu.cs.client.dto.PageDto["list"]->com.github.pagehelper.Page[0]->com.shuidihuzhu.cs.client.dto.servicesummary.remake.ServiceSummaryDto_$$_jvstc0_1["handler"])
問題原因
<resultMap id="BookWithAuthor2" type="org.javaboy.mybatis.model.Book" extends="BaseResultMap">
<association property="author" javaType="org.javaboy.mybatis.model.Author"
select="org.javaboy.mybatis.mapper.BookMapper.getAuthorById" column="aid" fetchType="lazy"/>
</resultMap>
<select id="getBookById2" resultMap="BookWithAuthor2">
select * from book where id=#{id};
</select>
比如如上的查詢, 顯式的寫了 fetchType="lazy"。 Mybatis會默認開啓懶加載,會先查Book, 不會查Author,這導致返回的時候,Json序列化失敗。
解決辦法
既然是懶加載導致的問題,那我們把懶加載關閉就好。
更改標籤爲 fetchType="eager"。
即一次性查出所有的,序列化就會成功