Finishing off my 'make folders from database' class
The below is a class for making local folders from database entries where each folder has a name, id and parent-id. I have put it together as best I can but do not know enough to finish it off.
I need to "just grab the folder with id 0 and start building your Files on the disk, using folder.getChildren() as a convenient way to move down the tree then just mkdirs()" as told to me in another post but I do not understand how and where to do it. Please help
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 );
//intFolderId = Integer.valueOf(FolderId);
/开发者_StackOverflow/intParentId = Integer.valueOf(FolderId);
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);
}
}
}
Basically reading hierachies from the database is not trivial, but if you read one level per query that should be doable.
What you need to do is the following:
- select all folders that have no parent, those are your root folders
- create the folders if they don't exist already
- repeat the following until you don't get any more results from the db
- select all folders whose parent id is the id of the folders read in the previous iteration (or the parents)
- assign the read subfolders to their parents based on the parent id
- create the read subfolders in their parents
This would allow you to use a breadth-first approach, i.e. you read one level of folders per iteration and map the children to the parents using parent_id.
As an alternative you could read the children for a single parent and iterate over the hierarchy in a depth-first manner.
精彩评论