提问人:Coder 提问时间:11/11/2023 最后编辑:philipxyCoder 更新时间:11/12/2023 访问量:92
将带有外键的数据库转换为模型,如何处理关系 [已关闭]
Turning a DB with foreign keys into models, how to deal with the relationships [closed]
问:
我正在做一个 Dart 项目,我需要在我的应用程序中表示两个类之间的关系。
CREATE TABLE department
(
department_id INTEGER PRIMARY KEY,
department_name TEXT
);
CREATE TABLE employee
(
employee_id INTEGER PRIMARY KEY,
employee_name TEXT,
department_id INTEGER,
FOREIGN KEY (department_id) REFERENCES department(department_id)
);
案例一:
class Department
{
int departmentId;
String departmentName;
}
class Employee
{
int employeeId;
String employeeName;
int departmentId;
}
案例二:
class Employee
{
int employeeId;
String employeeName;
}
class Department
{
int departmentId;
String departmentName;
List<Employee> employees;
}
我应该使用其中哪一个?
第一种情况对数据库有更好的表示形式;但是,获取物品会很烦人,因为我不能再这样做了.Department.employee
在第二种情况下,很难来回转换它们,因为 toMap 和 fromMap 需要排除对部门内部员工的引用,然后才能将它们保存在数据库中。
答:
除非您有充分的理由这样做,否则不要在所有字段名称前面加上表/实体名称。
以下是相关模型的规范定义:
class Department
{
// fields:
int id;
String name;
// relations:
List<Employee> employees;
}
class Employee
{
// fields:
int id;
String name;
// relations:
Department department;
}
上面的代码只是为了说明在对象图中使用直接对象引用的基本思想。一般来说,遍历这些模型是不平凡的,因为生成的图形是循环的,但使用 id 而不是直接引用并不能使这个问题变得更简单:即使使用间接引用,结构仍然是循环的。
使用 O/RM 时,通常可以将一些属性附加到关系属性(在 OR/M 术语中称为导航属性)来控制模型验证/生成/获取/保存策略。
我应该使用其中哪一个?
两者,以及其他数据结构。没有单一的“灵丹妙药”。
根据您目前正在开发的应用程序的功能,您可以在以下数据结构之一中表示数据库设计...用于该特定功能。
请记住,数据的内存 (Java) 表示形式只是特定时间点真实数据库数据的陈旧副本。真实数据在数据库中,在您读取后可能已经更改了一微秒。
当您为特定目的读取数据时,每个 Java 数据结构都必须适合一个(或几个)特定功能。数据结构模型并非旨在成为整个应用程序的单一解决方案。
上一个:数据库 ERD 问题 [已结束]
下一个:EERD 中的全不相交与 U 型
评论