如何在没有 属性 的情况下基于实体 类 将数据插入 JavaFX TableView?

How to insert data into JavaFX TableView, based on Enity Classes, without a Property?

我这里有一个实体 Class

@Entity
@Table(name = "student", catalog = "studdb", schema = "")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Student.findAll", query = "SELECT s FROM Student s"),
    @NamedQuery(name = "Student.findById", query = "SELECT s FROM Student s WHERE s.id = :id"),
    @NamedQuery(name = "Student.findByName", query = "SELECT s FROM Student s WHERE s.name = :name"),
    @NamedQuery(name = "Student.findBySurname", query = "SELECT s FROM Student s WHERE s.surname = :surname")})
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "Name")
    private String name;
    @Basic(optional = false)
    @Column(name = "Surname")
    private String surname;

    public Student() {
    }

    public Student(Integer id) {
        this.id = id;
    }

    public Student(Integer id, String name, String surname) {
        this.id = id;
        this.name = name;
        this.surname = surname;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

这是我的 JPA 控制器:

public class StudentJpaController implements Serializable {

public StudentJpaController(EntityManagerFactory emf) {
    this.emf = emf;
}
private EntityManagerFactory emf = null;

public EntityManager getEntityManager() {
    return emf.createEntityManager();
}

public void create(Student student) throws PreexistingEntityException, Exception {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        em.persist(student);
        em.getTransaction().commit();
    } catch (Exception ex) {
        if (findStudent(student.getId()) != null) {
            throw new PreexistingEntityException("Student " + student + " already exists.", ex);
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public void edit(Student student) throws NonexistentEntityException, Exception {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        student = em.merge(student);
        em.getTransaction().commit();
    } catch (Exception ex) {
        String msg = ex.getLocalizedMessage();
        if (msg == null || msg.length() == 0) {
            Integer id = student.getId();
            if (findStudent(id) == null) {
                throw new NonexistentEntityException("The student with id " + id + " no longer exists.");
            }
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public void destroy(Integer id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Student student;
        try {
            student = em.getReference(Student.class, id);
            student.getId();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The student with id " + id + " no longer exists.", enfe);
        }
        em.remove(student);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public List<Student> findStudentEntities() {
    return findStudentEntities(true, -1, -1);
}

public List<Student> findStudentEntities(int maxResults, int firstResult) {
    return findStudentEntities(false, maxResults, firstResult);
}

private List<Student> findStudentEntities(boolean all, int maxResults, int firstResult) {
    EntityManager em = getEntityManager();
    try {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Student.class));
        Query q = em.createQuery(cq);
        if (!all) {
            q.setMaxResults(maxResults);
            q.setFirstResult(firstResult);
        }
        return q.getResultList();
    } finally {
        em.close();
    }
}

public Student findStudent(Integer id) {
    EntityManager em = getEntityManager();
    try {
        return em.find(Student.class, id);
    } finally {
        em.close();
    }
}

基于 javaFX 8.0 的 TableView API, 我们可以创建一个 TableView<Student> ,并根据 class 学生的属性创建一些列, 但问题是,我的学生 class 没有 前任。 SimpleStringProperty对于字符串对象

SimpleIntegerProperty 用于整数对象或 PDT (int)

所以这是我的 TableView 示例的 FXMLController,它获取数据 从数据库 Table 使用实体Classes 和 JPA,

public class TableViewExController implements Initializable {

@FXML
private TableView<Student> tableView;

@FXML
private TableColumn<Student, String> nameCol;

@FXML
private TableColumn<Student, String> SurCol;

public ObservableList<Student> getStudentList() {
    ObservableList<Student> data = FXCollections.observableArrayList();
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaApplication1PU");
    StudentJpaController st = new StudentJpaController(emf);
    List<Student> list = st.findStudentEntities();
    for (Student stu : list) {
        data.add(stu);
    }
    return data;
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    tableView = new TableView<>();
    nameCol = new TableColumn<>("Name");
    nameCol.setCellValueFactory(new PropertyValueFactory<>("nameProperty"));
    SurCol = new TableColumn<>("Surname");
    SurCol.setCellValueFactory(new PropertyValueFactory<>("surnameProperty"));
    tableView.setItems(getStudentList());
    for (Student s : getStudentList()) {
        System.out.println(s.getName() + " : " + s.getSurname());
    }
    tableView.getColumns().addAll(nameCol, SurCol);
}

}

当启动 args 时,主要 class 就是这个..

@Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("TableViewEx.fxml"));
    Pane pane = (Pane)loader.load();
    Scene sc = new Scene(pane);
    primaryStage.setScene(sc);
    primaryStage.show();
}

public static void main(String [] args){
    launch(args);
}

结果是 table,没有数据.. 我如何在 TABLE 中添加项目,而没有学生 CLASS 中的 属性 属性?

问题是
1 PropertyValueFactory<>("nameProperty")); 需要与实体bean匹配
2. 需要 fxml 而不是像“tableView = new TableView<>();”这样的语句 请参阅下面的带有模拟数据的 soln

// sample.Controller
    @FXML
    private TableView<Student> tableView;

    @FXML
    private TableColumn<Student, String> nameCol;

    @FXML
    private TableColumn<Student, String> SurCol;


    @FXML
    public final void initialize() {

        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        SurCol.setCellValueFactory(new PropertyValueFactory<>("surname"));
        tableView.setItems(getStudentList());

    }

    public ObservableList<Student> getStudentList() {
        ObservableList<Student> data =  
                     FXCollections.observableArrayList();
        for (int i = 0; i < 10; i++) {
            data.add(new Student(i, String.format("%sth name", i), 
            String.format("%sth Surname", i)   ));

        }
        return data;
    }

FXML

<StackPane fx:controller="sample.Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" >


    <TableView fx:id="tableView" VBox.vgrow="ALWAYS">
        <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
        </columnResizePolicy>
        <columns>
            <TableColumn fx:id="nameCol" text="Name" />
            <TableColumn fx:id="SurCol" text="Surname" />
        </columns>
    </TableView>


</StackPane>