If I have a deep nested table (5 tier) relationship, what is a good method in retrieving the correlating data so that I can store them in my Java objects?
Here's what the tables look like:
___________ ___________ ___________ ___________ ___________
| Table A | | Table B | | Table C | | Table D | | Table E |
|___________| |___________| |___________| |___________| |___________|
| tableA_id | | tableB_id | | tableC_id | | tableD_id | | tableE_id |
| some_data | | some_data | | some_data | | some_data | | some_data |
|___________| | tableA_id | | tableB_id | | tableC_id | | tableD_id |
|___________| |___________| |___________| |___________|
METHOD 1 is what I'm currently using
- A query to retrieve a row from the base table. I store this in ObjectA.
- A query to retrieve all rows from the second table matching the id of the previous query. I store them in List<ObjectB> inside ObjectA.
- For each ObjectB, a query to retrieve all rows of the third table matching the id of ObjectB. I store these in List<ObjectC> inside ObjectB.
- For each ObjectC, a query to retrieve all rows of the fourth table matching the id of ObjectC. I store these in List<ObjectD>inside ObjectC.
- For each ObjectD, a query to retrieve all rows of the fifth table matching the id of ObjectD. I store these in List<ObjectE>inside ObjectD.
- All of the above queries sit within a "db.beginTransaction" and a "db.endTransaction" statement so that if one query fails unnaturally (errors), ObjectA will not be created.
The method above has a lot of looping, and a lot of queries. I get the feeling that this isn't the way to go because I'm constantly sending and receiving data from the database at every iteration of my loops.
METHOD 2
Another method I was thinking of is to join the 5 tables together. This leads to just one query but the looping remains, because I will need to group and loop through the foreign id of each tier. At least this way, I get all the information up front. But I don't know how to dissect the data into their respective object once I have them in one lump. Here's what my join looks like:
SELECT * FROM (((tableA
JOIN tableB ON tableA._id = tableB.tableA_id)
JOIN tableC ON tableB._id = tableC.tableB_id)
JOIN tableD ON tableC._id = tableD.tableC_id)
JOIN tableE ON tableD._id = tableE.tableD_id
Now how would I go through the cursor in order to dissect the join and put their respective data into the right object?