我有一个类,它引入一个id,name和(如果需要)parent-id,它将这些转换为对象,然后链接它们。
如果你看起来正确,你会看到我现在想要修复的内容,文件夹对象知道他们是否有孩子和/或父母,但如果我要在这里运行mkDirs(),它只适用于两个级别(root,子文件夹)但如果有多个级别(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!");
}
}
}
答案 0 :(得分:1)
看起来您可以/应该将目录创建逻辑分解为自己的函数,然后使其递归。这应该让你能够制作“无限的”深度目录层次结构。
旁注:在循环中重复进行DB调用非常低效。尝试单个选择,然后循环结果。如果需要,您可以使用SQL的'IN'运算符来过滤结果: http://www.w3schools.com/sql/sql_in.asp