Mybatis通过colliection属性递归获取菜单树
生活随笔
收集整理的這篇文章主要介紹了
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 {@Autowiredprivate CategoryDao categoryDao;/* (non-Javadoc)* @see com.xdw.service.CategoryService#getCategoryList()*/@Overridepublic List<Category> getCategoryList() {// TODO Auto-generated method stubreturn categoryDao.getCategoryList();}}4、controller層
@RequestMapping("/getCategoryTree") @ResponseBodypublic List<Category> getCategoryTree() {return categoryService.getCategoryList();} 此時基于SSM的操作已經完畢,核心就是在寫mybatis的xml,可以在瀏覽器中查看運行結果,返回的是json數據。運行結果如下create by xiadewang
轉載于:https://www.cnblogs.com/xiadewang/p/8879837.html
總結
以上是生活随笔為你收集整理的Mybatis通过colliection属性递归获取菜单树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: xshell 快速复制打开之前用过的ss
- 下一篇: 天猫11.11:手机淘宝 521 性能优