2011-09-27 107 views
0

我有一個類,它包含一個id,name和(如果需要的話)parent-id,它將這些轉換爲對象,然後將它們鏈接起來。建立鏈接目錄

如果你看看正確的結尾,你會看到我正在嘗試修復的時刻,文件夾對象知道他們是否有孩子和/或父母,但如果我在這裏運行mkDirs(),它只會工作爲兩個級別(根,子文件夾),但如果有多級(root/folder1/folder1)它不會工作。

任何想法如何解決這個問題?

package stable; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.HashMap; 
import java.util.Map; 
public class Loop { 

public static void main(String[] args) { 
    int PID = 0; 

    int RepoID = 1; 
    Connection con = null; 
    String url = "jdbc:mysql://localhost/document_manager"; 
    String user = "root"; 
    String password = "Pa55w0rd"; 
    try { 
     con = DriverManager.getConnection(url, user, password); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 
    Map<Integer,Folder> data = new HashMap<Integer,Folder>(); 
    while(PID < 50) 
    { 
    try {    
     Statement st = con.createStatement(); 
     ResultSet result = st.executeQuery("SELECT name, category_id, parent_id FROM categories WHERE parent_id = '"+PID+"' AND repository_id = '"+RepoID+"'"); 
     while (result.next()) 
     { 
      String FolderName = result.getString ("name"); 
      String FolderId = result.getString ("category_id"); 
      String ParentId = result.getString ("parent_id"); 
      int intFolderId = Integer.parseInt(FolderId); 
      int intParentId = Integer.parseInt(ParentId); 
      System.out.println(FolderId+" "+FolderName+" "+ParentId); 
      Folder newFolder = new Folder(FolderName, intFolderId, intParentId); 
      data.put(newFolder.getId(), newFolder); 
      } 
    } catch (SQLException ex) { 
     System.out.println(ex.getMessage()); 
    } 
    PID++; 
    } 
    for(Folder folder : data.values()) {  
     int parentId = folder.getParentFolderId(); 
     Folder parentFolder = data.get(parentId); 
     if(parentFolder != null) 
      parentFolder.addChildFolder(folder); 
     //Added 
     System.out.print("\n"+folder.getName()); 
     if(parentFolder != null) 
      System.out.print(" IS INSIDE "+parentFolder.getName()); 
     else 
      System.out.print(" HAS NO PARENT!"); 

    } 
} 
} 

回答

1

看起來你可以/應該將目錄創建邏輯分解爲它自己的函數,然後使其遞歸。這應該讓你能夠製作'無限'深度目錄層次結構。

備註:在循環中重複DB調用的效率非常低。嘗試一個選擇,然後通過結果循環。如果需要,可以使用SQL的'IN'運算符來篩選結果: http://www.w3schools.com/sql/sql_in.asp