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數據。運行結果如下
