I am designing data model in following way:
Table 1:
id: number
somedata: String
somedata: StringTable 2:
id: number
Table1_id: number
somedata: String
somedata: StringTable 3:
id: number
Table2_id: number
somedata: String
1st table is joined to 2nd table with one to many relationship. 2nd table is joined to 3rd table with one to many relationship. I am using java, JPA. I have to return JSON via rest api in following format:
{
"table1_id": 1,
"somedata": "somedata",
"table2_data": [
{
"table2_id": 1,
"somedata": "somedata",
"table3_data": [
{
"table3_id": 1,
"somedata": "somedata"
},
{
"table3_id": 2,
"somedata": "somedata"
}
]
},
{
"table2_id": 2,
"somedata": "somedata",
"table3_data": [
{
"table3_id": 3,
"somedata": "somedata"
},
{
"table3_id": 4,
"somedata": "somedata"
}
]
}
]
}
If I use mysql and above table structure I will need to use minimum 3 database calls to fetch from 3 tables separately and will have to construct my json. Is there a way where I can reduce database calls and also reduce effort to construct my json? I am open to change database(mysql) also. I just need fast, optimised and best solution. Note that table1, table2 and table3 has different fields so I can not denormalize them to single table.
Sorry for bad formatting of json. Couldn't figure out how to show it here.
I already have seen this question and my question is different than this: Nested JSON from 3 one-to-many Tables
Edit: I got the answer here: https://dba.stackexchange.com/questions/164370/nested-json-response-from-3-one-to-many-tables
I recommend you to perform join first of all three table and then you can manipulate the outcome of the database query(depend on your select statement) as per your requirement as i see you created a json object of the tables.For example there is three tables Category Subcategory and Items lets see how i perform join and then fetch json data according to requirement:-
$query = "SELECT
items.id, items.category_id, items.sub_category_id, items.price_per_quantity, items.discounted_price, items.total_quantity, items.image, items.status, items.name as name, sub_categories.name as sub_category_name, categories.name as category_name
FROM items
INNER JOIN sub_categories ON sub_categories.id = items.sub_category_id
INNER JOIN categories ON categories.id = items.category_id";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.