I have a webapp that has an object that contains a collection of itself. I am struggling with how to model this in a MySQL database. It is a Task object that contains a list of subtasks. Here is what the class looks like:
Task.java
public class Task{
private int taskID;
private String name;
private String details;
private List<Task> subTasks
...other properties
public Task(int taskID, String name, String details){
this.taskID = taskID;
this.name = name;
this.details = details;
this.subTasks = new ArrayList<>();
}
Getters and Setters here...
}
Through some research and thinking it through on my own I have come up with one possible solution. I have an image of a UML diagram of it but can't post it since I just joined and my SO rep isn't high enough yet. So I did my best to show it with characters below:
--------------------- -------------------
| Task | | SubTaskMap |
--------------------- 1 __∞_|-----------------
| int taskID |----|__∞_|int subTaskID |
| String taskName | |int parentTaskID |
| String taskDetail | -------------------
--------------------
So both subTaskID and parentTaskID are primary keys in the table SubTaskMap as well as foreign keys to taskID in the table Task (again, all of them are for Task objects in Java). From what I can tell, to run queries to find all tasks associated with a parentTaskID on this setup I would have to create an alias of the Task table.
I modeled this all in MS Access and for a query to get all Tasks associated with a parentTaskID of 5, I designated a join between Task.taskID with SubTaskMap.subTaskID and another join between an alias table Task_Copy and SubTaskMap that linked Task_copy.taskID with SubTaskMap.parentTaskID got a SQL query like this:
SELECT Task.taskName, SubTask.parentTaskID
FROM Task AS Task_Copy INNER JOIN (Task INNER JOIN SubTask ON Task.taskID = SubTask.subTaskID) ON Task_Copy.taskID = SubTask.parentTaskID
WHERE (((SubTask.parentTaskID)=5));
So is this a good way to go about solving this problem or is there a better way?
Thanks for any help!