如何通过 Hibernate 将 H2 数据库项目打印到 JavaFx SceneBuilder 准备的 TableView 上

Posted

技术标签:

【中文标题】如何通过 Hibernate 将 H2 数据库项目打印到 JavaFx SceneBuilder 准备的 TableView 上【英文标题】:How to print H2 database items onto a JavaFx SceneBuilder prepared TableView via Hibernate 【发布时间】:2014-02-18 09:40:10 【问题描述】:

我一直在尝试通过 Hibernate 将 H2 数据库项目打印到 JavaFx SceneBuilder 准备的 TableView 上,但失败得很惨。请帮我弄清楚我哪里出错了。

这是我的控制器类:

import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class FXMLDocumentController implements Initializable 

    @FXML
    private TableView<NewBeautifulKiwi> KIWI_TABLE;

    @FXML
    private TableColumn<NewBeautifulKiwi, Integer> KiwiId;

    @FXML
    private TableColumn<NewBeautifulKiwi, String> Kiwi;

    @Override
    public void initialize(URL url, ResourceBundle rb) 
        System.out.println("Now we print onto out onto our TableView");
        KiwiId.setCellValueFactory(new PropertyValueFactory<NewBeautifulKiwi, Integer>("KiwiId"));
        Kiwi.setCellValueFactory(new PropertyValueFactory<NewBeautifulKiwi, String>("Kiwi"));
        KIWI_TABLE.getItems().setAll(gobbledyGook());

    

    private ObservableList<NewBeautifulKiwi> gobbledyGook() 
        ObservableList<NewBeautifulKiwi> data;
        data = FXCollections.observableArrayList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try 
            transaction = session.beginTransaction();
            List courses = session.createQuery("from KIWI_TABLE").list();
            for (Iterator iterator = courses.iterator(); iterator.hasNext();) 
                NewBeautifulKiwi course = (NewBeautifulKiwi) iterator.next();
                System.out.println(course.getKiwi());

                data.add(course);
            
            transaction.commit();
         catch (HibernateException e) 
            transaction.rollback();
            e.printStackTrace();
         finally 
            session.close();
        
        return data;
    


FXML 文件:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="293.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="tableviewfix.FXMLDocumentController">
  <children>
    <TableView fx:id="KIWI_TABLE" prefHeight="293.0" prefWidth="320.0" tableMenuButtonVisible="false" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
      <columns>
        <TableColumn prefWidth="75.0" text="KiwiId" fx:id="KiwiId" />
        <TableColumn prefWidth="75.0" text="Kiwi" fx:id="Kiwi" />
      </columns>
    </TableView>
  </children>
</AnchorPane>

POJO 类:

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity(name = "KIWI_TABLE")
public class NewBeautifulKiwi implements Serializable 

    @Id
    @GeneratedValue
    private int KiwiId;
    private String Kiwi;

    public int getKiwiId() 
        return KiwiId;
    

    public void setKiwiId(int KiwiId) 
        this.KiwiId = KiwiId;
    

    public String getKiwi() 
        return Kiwi;
    

    public void setKiwi(String Kiwi) 
        this.Kiwi = Kiwi;
    

休眠.cfg:

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:file:C:/WAKILI/WAKILIdb</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

    <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>




        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <!-- Names the annotated entity class -->
        <mapping class="tableviewfix.NewBeautifulKiwi"/>

    </session-factory>

</hibernate-configuration>

编辑:

我刚刚意识到所有新条目的 @GeneratedValue 都为 0。我认为这就是问题所在。如何为新条目分配越来越多的数字,例如:

This is Entry Number: First     Entry - and the @GeneratedValue Number is: 0
This is Entry Number: Second    Entry - and the @GeneratedValue Number is: 1
This is Entry Number: Third     Entry - and the @GeneratedValue Number is: 2
This is Entry Number: Fourth    Entry - and the @GeneratedValue Number is: 3

如果@GeneratedValue 正确递增,我应该得到上面的输出,但我得到的是这个:

This is Entry Number: First     Entry - and the @GeneratedValue Number is: 0
This is Entry Number: Second    Entry - and the @GeneratedValue Number is: 0
This is Entry Number: Third     Entry - and the @GeneratedValue Number is: 0
This is Entry Number: Fourth    Entry - and the @GeneratedValue Number is: 0

所有项目的 @GeneratedValue 为 0。

执行数据库条目的相关类如下所示:

public class PersistNewBeautifulKiwi 

    public void doKiwi(String kiwi) 
        NewBeautifulKiwi newBeautifulKiwi = new NewBeautifulKiwi();
        newBeautifulKiwi.setKiwi(kiwi);

        HibernateUtil.getSessionFactory();

        System.out.println("\n" + "This is Entry Number: " + newBeautifulKiwi.getKiwi() + " - and the @GeneratedValue Number is: " + newBeautifulKiwi.getKiwiId());
    

【问题讨论】:

你得到的错误是什么? 嘿@VinayVeluri。请看更新部分!!!!我刚刚意识到所有新条目的 @GeneratedValue 都为 0。 【参考方案1】:

为上述指定generator

 @Id
 @GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")
 @Column(name="CUST_ID")
 public Long getId()  return id; 

 Example 2:

 @Id
 @GeneratedValue(strategy=TABLE, generator="CUST_GEN")
 @Column(name="CUST_ID")
 Long id;

这里有很好的解释:Hibernate: rundown on how @GeneratedValue works

【讨论】:

我按照您的建议进行了尝试,但现在运行项目时出现此错误:注意:Hibernate JPA 2 Static-Metamodel Generator 1.1.1.Final warning: Supported source version 'RELEASE_6' from注释处理器 'org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor' 小于 -source '1.7' 1 个警告【参考方案2】:

在你的 POJO 类上,试试这个:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

而不是这个:

@Id
@GeneratedValue

【讨论】:

以上是关于如何通过 Hibernate 将 H2 数据库项目打印到 JavaFx SceneBuilder 准备的 TableView 上的主要内容,如果未能解决你的问题,请参考以下文章

java - 如何在java桌面应用程序中使用spring(事务)和hibernate创建嵌入式H2 DB?

未找到 Hibernate H2 数据库

如何将 CLOB 与 Hibernate 以及 Postgres 和 H2 一起使用

在数据库中使用带有 H2 的 Hibernate 时出错

使用 Hibernate 的存储过程在嵌入式 h2 数据库中失败

如何在 IntelliJ 和 H2 中创建 Hibernate 映射