在javafx中使用映射表(JPA)

时间:2015-06-28 08:03:18

标签: hibernate jpa javafx javafx-8 scenebuilder

我已经映射了一张表

import javafx.fxml.FXML;
import org.hibernate.annotations.Immutable;

import javax.persistence.*;
import java.util.List;

@Immutable
@Entity
@Table(schema = "dbo", name = "tCountry")
public class FaCountry {

    @Id
    @Column(name = "CountryID")
    private Long id;
    public Long getId() {
        return id;
    }

    @Column(name = "name")
    private String name;
    public String getName() {
        return name;
    }
}

如何在JavaFX SceneBuilder中使用它?我在SceneBuilder中创建了一个TableView,并将此TableView的fx:id命名为countryTable。我想我必须在Main Class中创建

private ObservableList<FaCountry> countryData = FXCollections.observableArrayList();

并将此ObservableList中的信息放入Controller

@FXML
    private TableView<FaCountry> countryTable;

但是如何将映射表中的数据放入此ObservableList中?我无法全面了解如何做到这一点。我对所有这些主题和Java都很陌生。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

            @FXML
            private TableView<FaCountry> countryTable; 
            private ObservableList<FaCountry> countryData = FXCollections.observableArrayList();
            private EntityManagerFactory emf;
            private EntityManager em;
            //  ...
                public void initialize(URL url, ResourceBundle rb) {
                emf = Persistence.createEntityManagerFactory("persistenceTest");
                em = emf.createEntityManager();
                TypedQuery<FaCountry> query = em.createQuery(
                        "SELECT e FROM FaCountry e", FaCountry.class);
                List<FaCountry> list = query.getResultList();
                countryData.addAll(list);
                countryTable.setItems(countryData);
    }