java - 使用 Hibernate 构建不起作用(仅限 Hibernate)

标签 java hibernate javafx build netbeans-8

我使用 JavaFx 和 Hibernate 创建了一个 Java 应用程序。 在我的 IDE 中一切正常。但是当我构建应用程序并启动 .jar 文件时,所有使用 Hibernate 的功能都不起作用。

我创建了另一个测试应用程序来向您展示我的代码:

这是我的主要类(class):

package testapp;

import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Testapp extends Application {

    @Override
    public void start(Stage primaryStage) {

        ComboBox<Test> cmbtest=new ComboBox<>();
        ObservableList<Test> l=FXCollections.observableArrayList(loadCmb());     
        StackPane root = new StackPane();      
        root.getChildren().add(cmbtest);
        cmbtest.setItems(l);
        Scene scene = new Scene(root, 300, 250);        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    public List<Test> loadCmb(){
        List<Test> list;
        SessionFactory sf;
        sf= NewHibernateUtil.getSessionFactory();       
        Session session = sf.openSession();
        Query query=session.createQuery("FROM Test test");        
        list=query.list();
        return list;   
        }

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">****</property>
    <mapping resource="testapp/Test.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

这是我的 NewHibernateUtil:

package testapp;

import java.io.File;
import javax.imageio.spi.ServiceRegistry;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class NewHibernateUtil {

    private static SessionFactory sf;
    private static ServiceRegistry serviceRegistrry;    

    static {
        try {   
             File file=new File("src/testapp/hibernate.cfg.xml");
            Configuration cfg= new Configuration().configure(file);            
            StandardServiceRegistryBuilder sb= new StandardServiceRegistryBuilder();
            sb.applySettings(cfg.getProperties());
            StandardServiceRegistry standardServiceRegistry= sb.build();
            sf = cfg.buildSessionFactory(standardServiceRegistry);
        } catch (Throwable ex) {            
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sf;
    }
}

这是我唯一的类,是从 MySql 中的数据库创建的

package testapp;
// Generated 24/10/2016 01:53:10 PM by Hibernate Tools 4.3.1



/**
 * Test generated by hbm2java
 */
public class Test  implements java.io.Serializable {


     private String name;
     private Integer number;

    public Test() {
    }


    public Test(String name) {
        this.name = name;
    }
    public Test(String name, Integer number) {
       this.name = name;
       this.number = number;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public Integer getNumber() {
        return this.number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }
}

mySql 是一张有 2 列的表 测试表: 姓名和号码

如果我在 IDE 中运行此程序,则应用程序运行正常,但当我构建应用程序时,.jar 文件无法正常工作。

这是我的构建的输出:

ant -f C:\\Users\\Dani-Fla-Mathi\\Documents\\NetBeansProjects\\testapp jfx-rebuild
init:
deps-clean:
Created dir: \testapp\build
Updating property file: \testapp\build\built-clean.properties
Deleting directory \testapp\build
clean:
init:
deps-jar:
Created dir: \testapp\build
Updating property file: \testapp\build\built-jar.properties
Created dir: \testapp\build\classes
Created dir: \testapp\build\empty
Created dir: \testapp\build\generated-sources\ap-source-output
Compiling 3 source files to \testapp\build\classes
Note:\testapp\src\testapp\Testapp.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Copying 3 files to \testapp\build\classes
compile:
Created dir: \testapp\dist
Copying 17 files to \testapp\dist\lib
Detected JavaFX Ant API version 1.3
Launching <fx:jar> task from C:\Program Files\Java\jdk1.8.0_05\jre\..\lib\ant-javafx.jar
Warning: From JDK7u25 the Codebase manifest attribute should be used to restrict JAR repurposing.
         Please set manifest.custom.codebase property to override the current default non-secure value '*'.
Launching <fx:deploy> task from C:\Program Files\Java\jdk1.8.0_05\jre\..\lib\ant-javafx.jar
jfx-deployment-script:
jfx-deployment:
jar:
jfx-rebuild:
BUILD SUCCESSFUL (total time: 2 seconds)

如果您需要更多信息,请告诉我

最佳答案

您正在从一个文件加载 hibernate 配置,该文件的路径是相对于当前工作目录指定的:

File file=new File("src/testapp/hibernate.cfg.xml");
Configuration cfg= new Configuration().configure(file);  

显然,当您将应用程序部署为 jar 文件时,此文件路径将不再有意义(除此之外,src 文件夹将不会包含在 jar 文件中,并且将在运行时不可用)。

您应该将配置文件指定为资源,并给出 URL:

URL resource = NewHibernateUtil.class.getResource("hibernate.cfg.xml");
Configuration cfg= new Configuration().configure(resource);            

假设其他所有内容都已正确部署,即配置文件已部署到 jar 文件,hibernate jar 位于类路径上等,这应该可以解决问题。

关于java - 使用 Hibernate 构建不起作用(仅限 Hibernate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221167/

相关文章:

java在循环中超出范围

java - Bouncy CaSTLe ECC Key Pair Generation为EC公钥点坐标生成不同大小

java - 过多的线程在 Android 中是个坏主意吗?

java - 如何在Hibernate中映射多个一对多关联

java - Hibernate 用户和 friend JsonReference

java - spring hibernate乐观锁问题

Java:如何将 Hibernate 命名 SQL 查询(在 XML 文件中)的结果映射到带注释的实体

Windows 上的 JavaFX GUI 线程和锁定屏幕

java - IntelliJ Idea JavaFX 调试问题

java - 将 JavaFX 中的折线图和散点图组合成多个系列