尝试在JavaFX TableView中显示数据库中的数据时遇到一个小问题。
我有一张学生表
user_id | name | nick | password | surname | classroom_id
---------|-----------|-----------|-----------|-----------|--------------
2 | AAA | studentA | test123 | AAA | 1
3 | BBB | studentB | test321 | BBB | 1
此表已连接到“课堂表”
classroom_id | classrooName | classroomYear
--------------|--------------|-------------
1 | TestClass | 2016/2017
我正在使用此查询让所有学生与他们所属的课堂在一起,这里没有问题。当我尝试打印出值时,一切都是正确的。
Select student from Student student Join Fetch student.classroom
现在,实际问题是,课堂名称和课堂年份没有显示在TableView中,如this(Jméno - 姓名,Příjmení - 姓氏,尼克 - 尼克,特里达 - 课堂名称,Rok-课堂年)
这两列的单元格值工厂是
classroomNameColumn.setCellValueFactory(new PropertyValueFactory<>("classroomName"));
classroomYearColumn.setCellValueFactory(new PropertyValueFactory<>("classroomYear"));
现在,我设法获取所有数据的唯一方法是将classroomName和classroomYear添加到我的Java类中,这些类在数据库中添加了2个额外的列。这种方式与我认为加入id的目的相悖,是否有更好的方法可以让我在TableView中显示Classroom数据?
编辑:以下是学生和课堂作为Java课程
@Entity
public class Student extends User{
private Classroom classroom;
public Student() {
}
public Student(String name, String surname, String nick, String password, Classroom studentClassroom) {
super(name, surname, nick, password);
this.classroom = studentClassroom;
}
@ManyToOne
@JoinColumn(name = "classroom_id")
public Classroom getClassroom() {
return classroom;
}
public void setClassroom(Classroom classroom) {
this.classroom = classroom;
}
}
@Entity
public class Classroom {
private SimpleStringProperty classroomName = new SimpleStringProperty();
private SimpleStringProperty classroomYear = new SimpleStringProperty();
private int classroom_id;
public Classroom() {
}
public Classroom(String name, String year) {
classroomName.set(name);
classroomYear.set(year);
}
@Column(nullable = false)
public String getClassroomName() {
return classroomName.get();
}
public SimpleStringProperty nameProperty() {
return classroomName;
}
public void setClassroomName(String name) {
this.classroomName.set(name);
}
@Column(nullable = false)
public String getClassroomYear() {
return classroomYear.get();
}
public SimpleStringProperty classroomYearProperty() {
return classroomYear;
}
public void setClassroomYear(String year) {
this.classroomYear.set(year);
}
@Id
@GenericGenerator(name="id" , strategy="increment")
@GeneratedValue(generator="id")
public int getClassroom_id() {
return classroom_id;
}
public void setClassroom_id(int classroom_id) {
this.classroom_id = classroom_id;
}
}
答案 0 :(得分:0)
您使用的PropertyValueFactory
正在寻找Student
中名为classroomName
的属性,该属性显然不存在。您需要自己实现单元格值工厂:
// assuming you declared
TableColumn<Student, String> classroomNameColumn ;
// ...
classroomNameColumn.setCellValueFactory(cellData -> {
Student student = cellData.getValue();
Classroom classroom = student.getClassroom();
if (classroom == null) return new SimpleStringProperty("");
return classroom.nameProperty();
});
同样适用于教室年。