JavaFx table 查看,table 网关模式并加入

JavaFx table view, table gateway pattern and join

为了处理数据库中的数据,我实施了 table 数据网关。所以,我有两个 tables:

CREATE TABLE student (
   id INT,
   id groupId,
   name VARCHAR(100),
   surname VARCHAR(100)
);

CREATE TABLE group (
   id INT,
   name VARCHAR(100)
);

而且我有两个 DTO。严格来说,一个 DTO 对应一个 table

class Student{
   private int id;
   private int groupId;
   private String name;
   private String surname;
   //+getters and setters
}

class Group{
   private int id;
   private String name;
   //+getters and setters
}

我有两个 TableDataGateway classes 加载和保存 DTO 到数据库。

class StudentTableDataGateway extends AbstractTableDataGateway{
....
}
class GroupTableDataGateway extends AbstractTableDataGateway{
....
}

现在我想通过 javafx 使用以下列创建学生 table:

|Student ID|Student Name|Student Surname|Group Name|

我到此为止。我不明白如何为 table 视图构建数据以及下一步应该做什么。请帮助我。

编辑 1
最困难的部分(最让我困惑的是)是如何link 从学生对象中的组对象中获取数据?因为,在 Student class 字段 "private Group group" 中制作是非常不可取的。原因是,如果我们为每个 tableview 修改域 classes,它们将非常糟糕。例如,如果我们需要创建另一个 table 包含列的视图:

|student name|student surname|teacher name

那我们要不要再给 Student 添加一个字段 class?

如果您有 getter,您唯一需要做的就是为您的 table 创建一组 table 属性。示例:

TableView<Student> table = new TableView<>();
TableColumn<Student,Integer> userId = new TableColumn<>("User Id");
userId.setCellValueFactory(new PropertyValueFactory<>("id"));

这将在您的 Student 对象 class 中查找 getId() 并从中添加数据。

唯一棘手的部分是组名,因为它在不同的 class 中。我可能只在 Student class 中包含辅助方法。你不需要在那里有任何 属性 。只需要有类似getter的方法

  public String getGroupName() {
      return ""//Code to find group name here;
  }

这里是您在这种情况下需要的所有代码:

    ObservableList<Student> students = FXCollections.observableArrayList();
    students.addAll(one);

    TableView<Student> table = new TableView<>();
    TableColumn<Student,Integer> userId = new TableColumn<>("User Id");
    userId.setCellValueFactory(new PropertyValueFactory<>("id"));

    TableColumn<Student,String> groupName = new TableColumn<>("Group Name");
    groupName.setCellValueFactory(new PropertyValueFactory<>("groupName"));
    TableColumn<Student,String> name = new TableColumn<>("User Name");
    name.setCellValueFactory(new PropertyValueFactory<>("name"));

    TableColumn<Student,String> surname = new TableColumn<>("User Surname");
    surname.setCellValueFactory(new PropertyValueFactory<>("surname"));

    table.getColumns().addAll(userId,groupId,name,surname);
    table.setItems(students);

但 groupName 总有其他选项:

1) 创建自定义 CellValueFactory 和 setCellValueFactory()

   groupName.setCellValueFactory(data->{
           Student student = data.getValue();
           String strGroupName = "";// calculate group name for...
           return new ReadOnlyStringWrapper(strGroupName);
        }
    );

2) 使用您需要的所有 getter 创建缓冲区对象