Mybatis通过colliection属性递归获取菜单树

1、现有商品分类数据表category结构如下,三个字段都为varchar类型


2、创建商品分类对应的数据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();
}

3、创建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>

4、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();
    }

}

4、controller层

@RequestMapping("/getCategoryTree")
@ResponseBody
    public List<Category> getCategoryTree() {
        return categoryService.getCategoryList();
    }
此时基于SSM的操作已经完毕,核心就是在写mybatis的xml,可以在浏览器中查看运行结果,返回的是json数据。运行结果如下
 
 

create by xiadewang

posted @ 2018-04-19 08:57  独王  阅读(4777)  评论(0编辑  收藏  举报