Mybatis查詢之級聯查詢

springboot+mybatis+Oracle 級聯查詢方法遇到的問題及解決方法

1.上代碼:

首先 mybatis 級聯查詢方法:

<resultMap id="resultMap" type="com.test.entity.SysMenu">
    <id column="ID" property="id" />
    <result column="MENU_NAME" property="menuName" />
    <result column="MENU_URL" property="menuUrl" />
    <result column="PARENT _ID" property="parentId" />
<collection column="ID" property="childrenList" ofType="com.test.entity.SysMenu" javaType="java.util.ArrayList" select="getSubChargeItem"/>
   </resultMap>
<!-- 獲取一次菜單 -->
<select id="getMenuListPage" parameterType="com.seari.entity.SysMenu" resultMap="resultSubParentMap">
    SELECT
        menu.ID,
        menu.MENU_NAME,
        menu.MENU_URL,
        menu.PARENT_ID 
    FROM SYS_MENU menu
    <where>
        PARENT_ID = '0'
        <if test="menuName != null and menuName != ''">
            and menu.MENU_NAME like '%'|| #{menuName}||'%'
        </if>
   </where>
</select>
<!-- 獲取子級數據 -->
<select id="getSubChargeItem" resultMap="resultSubParentMap" parameterType="string">
    SELECT
    menu.ID,
    menu.MENU_NAME,
    menu.MENU_URL,
    menu.PARENT_ID 
    FROM SYS_MENU menu
    WHERE PARENT _ID = #{ID}
</select>

實體對象:

@Data    
public class SysMenu implements Serializable{

   /**
    * 主鍵
    */
   private String id;
   /**
    * 菜單名稱
    */
   private String menuName;
   /**
    * 菜單跳轉路徑
    */
   private String menuUrl;
   /**
    * 菜單父級id
    */
   private String parentId;

   /**
    * 子級菜單
    */
   private ArrayList<SysMenu> children;

以上即可實現mybatis的遞歸獲取子父級列表

2.問題:

就是我在請求時,提示錯誤信息:

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.seari.entity.ResultBean[\"data\"]->java.util.HashMap[\"result\"]-
>com.github.pagehelper.PageInfo[\"list\"]->com.github.pagehelper.Page[0]-
>com.test.entity.SysMenu_$$_jvstb9c_0[\"childrenList\"]->java.util.ArrayList[0]-
>com.test.entity.SysMenu_$$_jvstb9c_0[\"handler\"])",

3.解決:

原因是mybatis級聯查詢開啓了“懶加載”導致json序列化出錯。

因此在<collection/>中關閉懶加載即可:fetchType="eager" 

FetchType.LAZY:懶加載,加載一個實體時,定義懶加載的屬性不會馬上從數據庫中加載

FetchType.EAGER:急加載,加載一個實體時,定義急加載的屬性會立即從數據庫中加載

修改:

<collection column="ID" property="children" ofType="com.seari.entity.SysMenu" fetchType="eager" javaType="java.util.ArrayList" select="getSubChargeItem"/>

或者

@JsonIgnoreProperties(value = {"handler"})
public class SysMenu implements Serializable{
}

作用爲:忽略序列化bean過程中拋出的某些異常。

至此 便可實現mybatis級聯查詢,

工作記錄,因此對於一些問題沒有深入瞭解,有不對之處,希望各位大佬指出,小弟定及時改正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章