Mybatis經過colliection屬性遞歸獲取菜單樹

一、現有商品分類數據表category結構以下,三個字段都爲varchar類型


二、建立商品分類對應的數據Bean

/**
 * 
 */
package com.xdw.dao;

import java.util.List;

import com.xdw.model.Category;

/**
 * @author xiadewang
 *2018年4月16日
 */
public interface CategoryDao {
    List<Category> getCategoryList();
}

三、建立CategoryDao.xml

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xdw.dao.CategoryDao">
     <!-- 初始化菜單樹 -->
     <!-- 這裏的id的值做爲下面的查詢返回結果resultMap的值 -->
     <!-- collection中的column屬性能夠爲多個值,這裏只有一個,它做爲下面遞歸查詢傳遞進去的參數 -->
     <!-- ofType和javaType屬性正好聯合構成了數據Bean類Category中的childrenList屬性的數據類型 -->
     <!-- select的值爲下面遞歸查詢的select標籤的id值 -->
    <resultMap type="Category" id="categoryTree">
        <result column="cid" property="cid" javaType="java.lang.String" />
        <result column="cname" property="cname" javaType="java.lang.String" />
        <result column="pid" property="pid" javaType="java.lang.String" />
        <collection column="cid" property="childrenList" ofType="Category" javaType="java.util.ArrayList" select="selectCategoryChildrenByCid"/>
    </resultMap>
    
    <!-- 先查詢菜單根級目錄 -->
    <!-- 這裏的返回結果必須爲resultMap,而且值爲上面構建的resultMap的id的值 -->
    <select id="getCategoryList" resultMap="categoryTree">
    
        select * from category where pid = 'root'
            
    </select>
    
    <!-- 再利用上次查詢結果colliection中column的值cid作遞歸查詢,查出全部子菜單 -->
    <!-- 這裏的返回結果必須爲resultMap,而且值爲上面構建的resultMap的id的值 -->
    <select id="selectCategoryChildrenByCid" resultMap="categoryTree" parameterType="String">
    
        select * from category where pid = #{cid}
            
    </select>
</mapper>

四、service層

/**
 * 
 */
package com.xdw.service;

import java.util.List;

import com.xdw.model.Category;

/**
 * @author xiadewang
 *2018年4月16日
 */
public interface CategoryService {
    List<Category> getCategoryList();
}

/**
 * 
 */
package com.xdw.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xdw.dao.CategoryDao;
import com.xdw.model.Category;
import com.xdw.service.CategoryService;

/**
 * @author xiadewang
 *2018年4月16日
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    /* (non-Javadoc)
     * @see com.xdw.service.CategoryService#getCategoryList()
     */
    @Override
    public List<Category> getCategoryList() {
        // TODO Auto-generated method stub
        return categoryDao.getCategoryList();
    }

}

四、controller層

@RequestMapping("/getCategoryTree")
@ResponseBody
    public List<Category> getCategoryTree() {
        return categoryService.getCategoryList();
    }
此時基於SSM的操做已經完畢,核心就是在寫mybatis的xml,能夠在瀏覽器中查看運行結果,返回的是json數據。運行結果以下
 
 

create by xiadewang

相關文章
相關標籤/搜索