在不少場合,咱們須要對錶中的數據對遞歸查詢。如如下狀況:java
1. 菜單分類中,咱們每每須要由一級菜單得到對應的子菜單。node
id | name | pid |
---|---|---|
1 | 圖書 | 0 |
2 | 服裝 | 0 |
3 | 兒童讀物 | 1 |
4 | 雜誌 | 1 |
5 | 卡通 | 3 |
6 | 睡前故事 | 3 |
咱們但願獲得的結果爲,由圖書能夠查到:mysql
{ 圖書: [ 雜誌, {兒童讀物:[卡通,睡前故事]} ] }
2. 在相似上述具備依賴關係的查詢時,咱們將父子依賴關係抽象成如下字段:算法
col | col_parent |
---|---|
value1 | value2 |
value2 | value3 |
由col中的value1查詢到col_parent值爲value2;
再由value2做爲col查詢,查詢到value3。
注:父依賴或子依賴只是稱呼不一樣而已。sql
value1-->value2-->value3
數據庫
value2-->value3
mybatis
針對上述問題,本文提出兩種解決方案。app
優勢
:框架已經封裝好了,不用深刻實現原理。缺點
:返回結果的結構固定,不能靈活處理。對結構的解析也較複雜。擴展性差select col_parent from table_name where col=#{col}
及本身的代碼便可優勢
:靈活性高。返回結構可擴展難點
:須要理解實現原理。demo說明
對於mysql中以下數據表結構:框架
id | code | parent_code |
---|---|---|
... | ... | ... |
目標:咱們要求經過code找到左右父code(包括祖輩code)ide
核心代碼(其餘實現代碼不作展現)
@Mapper public interface RelationTreeDao { List<RelationTreeDTO> selectAllParentsByCode(String code);
public class RelationTreeDTO { private String code; private String parentCode; private List<RelationTreeDTO> parentCodeList; //List嵌套自己,裝父節點信息 // getter and setter }
<?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.***.dao.RelationTreeDao"> <!----> <resultMap id="relationTreeMap" type="com.***.dto.RelationTreeDTO"> <result column="task_code" property="taskCode" jdbcType="VARCHAR" javaType="String"/> <result column="parent_code" property="parentCode" jdbcType="VARCHAR" javaType="String"/> <collection column="parent_code" property="parentCodeList" select="selectAllParentsByCode"> </collection> </resultMap> <!-- relation表中選擇全部的父節點 --> <select id="selectAllParentsByCode" parameterType="java.lang.String" resultMap="relationTreeMap"> SELECT `code`,`parent_code` FROM `relation` WHERE `code` = #{code} AND `parent_code` is not NULL </select> </mapper>
說明:
RelationTreeDTO
做爲查詢結果的映射對象,其中須要定義自嵌套的Listcolumn="parent_code"
再做爲參數#{code}
循環查詢。結果:
relationTreeDao.selectAllParentsByCode("yourCode");
查詢結果將會以RelationTreeDTO
對象返回,如有多條父依賴,將顯示在List的嵌套中。[ { "code": ***, "parentCode": ***, "parentCodeList": [ { "code": ***, "parentCode": ***, "parentCodeList": [] }, ... ] } ]
對於上述結果,咱們每每須要進一步獲取有用信息。如只須要一個List:
[code, parentCode, parentCode, parentCode,...]
因爲RelationTreeDTO
是一個樹結構,這就涉及到樹的遍歷。在此,以樹的深度優先搜索算法
,得到上述list。
/** * description:深度優先搜索DTO中的全部父節點 * @author wanghongbing whbing1991@gmail.com * @param treeDTO RelationTreeDTO待解析的樹結構對象 * @return list [0]存code, [1]開始存parents * 必定會有一個父節點,list長度>=2 */ @Override public List<String> depthFirst(RelationTreeDTO treeDTO) { //list [0]存code, [1]開始存parents List<String> list = new ArrayList<>(); list.add(treeDTO.getCode()); //list[0] ArrayDeque<RelationTreeDTO> stack = new ArrayDeque(); stack.push(treeDTO); while (!stack.isEmpty()){ RelationTreeDTO node =stack.pop(); list.add(node.getParentCode()); //獲取嵌套節點 List<RelationTreeDTO> parents = node.getParentCodeList(); if(parents !=null && parents.size() >0){ for (int i = parents.size()-1; i >=0 ; i--) { stack.push(parents.get(i)); } } } return list; }
至此,該方式級聯查詢結束。
上述實現,collection
結果爲固定的樹結構,在解析時,要使用算法(如DFS
)獲取樹種的節點信息。雖然在mapper查詢時,一次性得到了級聯結構,後續解析仍然複雜。下面介紹推薦方式。
@Mapper public interface RelationDao { List<TaskRelationDTO> selectParentByCode(String code); // 其餘表 List<TaskRelationDTO> selectOtherParentByCode(String code); }
public class TaskRelationDTO { private String code; private String parentCode; // getter and setter }
<?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" > <!-- recommended not modified but can be added --> <mapper namespace="com.***.dao.RelationDao"> <!--tag--> <resultMap id="relationMap" type="com.***.dto.RelationDTO"> <result column="code" property="code" jdbcType="VARCHAR" javaType="String"/> <result column="parent_code" property="parentCode" jdbcType="VARCHAR" javaType="String"/> </resultMap> <!-- a_relation表中選擇當前code的父節點 --> <select id="selectParentByCode" parameterType="java.lang.String" resultMap="relationMap"> SELECT `code`,`parent_code` FROM `relation` WHERE `code` = #{code} AND `parent_code` is not NULL </select> <!-- other_relation表中選擇當前code的父節點 --> <select id="selectOtherParentByCode" parameterType="java.lang.String" resultMap="relationMap"> SELECT `code`,`parent_code` FROM `other_relation` WHERE `code` = #{code} AND `parent_code` is not NULL </select> </mapper>
說明:上述查詢僅爲最簡單的sql查詢,咱們將遞歸查詢寫在業務方法中。
/** * * @param code 待查找父任務的子任務 * @return 返回的list.size()>=2 list[0]當前code,[1]之後去重後的無序parentsCode * 如:[tag-depend-2, path-depend-0-p, path-depend-2, tag-depend-0, path-depend-0] */ @Override public List<String> getAllParentsByCode(String code) { List<String> list = new ArrayList<>(); Set<String> parentSet = new HashSet<>(); ArrayDeque<String> stack = new ArrayDeque(); int count = 0; final int MAX_LOOP_COUNT = 50; // 初始化stack,將code放入stack stack.push(code); // 將code加入list。若是最終list.isEmpty(),代表沒有父節點,將其清空。故list長度最短爲2 list.add(code); while (!stack.isEmpty()){ // 若是入棧次數太多,代表可能出現環形依賴。強行終止 if(count++ > MAX_LOOP_COUNT){ LOGGER.error("code爲["+code+"]任務其父任務超過"+MAX_LOOP_COUNT+"個,請檢查是否有環形依賴"); list.addAll(parentSet); // 僅有taskCode,無parentCode時,將list清空 if(list.size() == 1){ list.clear(); } return list; } String childCode = stack.pop(); /** 可能會出現兩個表交叉依賴狀況,故有otherRelation */ List<RelationDTO> relation =relationDao.selectTagParentByCode(childCode); List<TaskRelationDTO> otherRelation =relationDao.selectOtherParentByCode(childCode); // 從relation表中查找pop()元素的父任務,將其加入stack if(!relation.isEmpty()){ for (int i = 0; i < relation.size(); i++) { String parent = relation.get(i).getParentCode(); //這個parent是須要的,同時要將其放入stack parentSet.add(parent); stack.push(parent); } } // 從otherRelation表中查找pop()元素的父任務,將其加入stack if(!otherRelation.isEmpty()){ for (int i = 0; i < otherRelation.size(); i++) { String parent = otherRelation.get(i).getParentCode(); //這個parent是須要的,同時要將其放入stack parentSet.add(parent); stack.push(parent); } } } list.addAll(parentSet); // 僅有taskCode,無parentCode時,將list清空 if(list.size() == 1){ list.clear(); } return list; }
原理
說明:上述原理,使用棧
(遞歸亦可,所謂遞歸,無非進棧出棧)來循環查詢。初始化時,將待查詢的code
入棧,第一次查詢時,該code
出棧,做爲參數查詢,若有查詢結果(一條或多條),將查詢到的結果進棧(放入棧中,下次循環計就能夠取出做爲參數輸入了!)。
如上述進行了兩個表的查詢,靈活。
mybatis
中的collection
標籤,不推薦使用。本人在項目實踐中已由該方式更改成方式2。parentCode
做爲code
再次查詢,看似複雜,理解原理就簡單。