/** * */ package com.xdw.dao; import java.util.List; import com.xdw.model.Category; /** * @author xiadewang *2018年4月16日 */ public interface CategoryDao { List<Category> getCategoryList(); }
<?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>
/** * */ 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(); } }
@RequestMapping("/getCategoryTree") @ResponseBody public List<Category> getCategoryTree() { return categoryService.getCategoryList(); }