mybatis嵌套result解析原理

package mybatis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Node{
	String id;
	List<Node> nodes=new ArrayList<Node>();
}
public class Main {
	static Map<String,Node> cache=new HashMap<String, Node>();
	
	//模擬查出來的數據 select * from A left join B left join C
	static String[][] resultSetRow={
			{"a1"	,"b1"	,"c1"},	
			{"a2"	,"b2"	,"c5"},
			{"a2"	,"b3"	,"c6"},
			{"a1"	,"b1"	,"c2"},
			{"a2"	,"b1"	,"c3"},
			{"a2"	,"b1"	,"c4"},

	};
	//爲了簡單模擬,沒有遞歸遍歷ResultMapping,只是簡單的控制了遞歸深度
	static int MAXN=2;
	static Node getRowValue(String[] resultSet,String combinedKey,Node partialObject,int n){
		Node rowValue=partialObject;
		if(rowValue==null){
			rowValue=new Node();
			rowValue.id= resultSet[n];
			
			
		}
	
		
		if(n+1<=MAXN){
			String cacheKey=combinedKey+resultSet[n+1];
			Node cacheNode=cache.get(cacheKey);
			Node nest=getRowValue(resultSet, combinedKey, cacheNode, n+1);
			if(cacheNode==null){
				rowValue.nodes.add(nest);
				cache.put(cacheKey, nest);
			}
		}
		return rowValue;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<Node> list=new ArrayList<Node>();
		for(int i=0;i<resultSetRow.length;++i){
			String key=resultSetRow[i][0];
			Node partialObject= cache.get(key);
			
			Node rowValue=getRowValue(resultSetRow[i], key, partialObject, 0);
			
			if(partialObject==null){
				cache.put(key, rowValue);
				list.add(rowValue);
			}
		}
		for(int i=0;i<list.size();++i){
			printNode(list.get(i), 0);
		}
	}
	
	static void printNode(Node node,int n){
		for(int i=0;i<=n;++i){
			System.out.print("---");
			
		}
		System.out.println(node.id);
		for(Node child:node.nodes){
			printNode(child, n+1);
		}
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章