我正在考慮創建一個包含一對多和多對多元素的模式。由于我在這件事上有點新手,所以我搜索了一些資源并遇到了兩種型別的示例;1. 將下層物件的內容放入上層,然后進行處理。第二種是創建外鍵,你覺得哪一種更正確?
1.
@Entity
public class User {
@PrimaryKey
public final int id;
public final String login;
public final String avatarUrl;
}
@Entity
public class Tweet {
@PrimaryKey
public long id;
public String body;
public String createdAt;
public long userId;
// this field will be ignored by Room, but still can be used in other places in the Twitter app
@Ignore
public User user;
}
@Entity
public class User {
@PrimaryKey
public final int id;
public final String login;
public final String avatarUrl;
}
@Entity(foreignKeys = @ForeignKey(entity = User.class,
parentColumns = "id",
childColumns = "userId",
onDelete = CASCADE))
public class Tweet {
@PrimaryKey
public long id;
public String body;
public String createdAt;
public long userId;
}
這兩個選項中哪一個是正確且高效的?
另外,這是我要創建的資料庫模式..你認為我應該做什么..請在我不知道 kotlin 的 java 中顯示示例
{
"UserDatabase":
[
{
"sql_id": 0,
"name": "Test Name",
"username": "null",
"gender": "male",
"profile_photo_path": "path",
"pro_version": true,
"date_of_birth": "01/01/0000",
"weight": 100,
"height": 186,
"waist_size": 0,
"neck_size": 0,
"hip_size": 0,
"bmr_formula": "Benedict",
"macro_formula": "Fitness",
"starting_date": "18/02/2022",
"saved_items":
[
{
"sql_id": 0,
"parent_id": 0,
"item_id": 0,
"item_name": "name",
"item_image": "item image",
"item_url": "url",
"item_editor": "editor"
}
],
"days":
[
{
"sql_id": 0,
"parent_id": 0,
"id": 0,
"date": "16/02/2022",
"weight": 96,
"steps": 25252525,
"taken_kcal": 257.56,
"burned_kcal": 27.86,
"carb": 25.52,
"protein": 5.2,
"fat": 8.4,
"water_ml": "3250",
"water_percent": 27.68,
"daily_water_list":
[
{
"sql_id": 0,
"parent_id": 0,
"id": 0,
"time": 1644999314504,
"water_ml": 300
}
],
"daily_meals":
[
{
"sql_id": 0,
"parent_id": 0,
"id": 0,
"food_meal_time": "Meal Time",
"food_name": "Name",
"food_image": "image url",
"food_kcal": 300.56,
"food_portion": "Portion"
}
]
}
]
}
]
}
uj5u.com熱心網友回復:
更好的方法是使用外鍵,因為這會強制參考完整性。
否則,除了在子級(ren)(推文)中包含父級(用戶)之外,幾乎沒有什么區別。這不是必需的(因為您有對父級的參考)并且它與規范化相矛盾(即它復制資料)。
進一步來說
添加外鍵引入了約束(規則),即參考父表(用戶)的子表(推文)中的值必須是父表中存在的值,否則會發生沖突。
如果父級被洗掉,CASCADE的onDelete操作將自動洗掉子級,從而有助于/簡化維護參照完整性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427908.html
