从JAR文件运行应用程序时找不到hibernate.cfg.xml错误

时间:2015-04-10 07:56:19

标签: java hibernate jar properties-file

我已将项目导出到JAR文件中。我在JAR中有 hibernate.cfg.xml 文件,我创建了 hibernate.properties 文件,更改休眠设置,而无需直接编辑 hibernate.cfg.xml 文件。但是通过运行JAR文件我得到的是异常,期望 hibernate.cfg.xml 文件存在于JAR文件的一侧。但是我只想将 hibernate.properties 文件放在JAR文件之外来提供数据库设置。

控制台中的异常:

INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibern
ate.cfg.xml not found
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.lang.ExceptionInInitializerError
        at DataLayer.HibernateAdapter.buildSessionFactory(HibernateAdapter.java:
37)
        at DataLayer.HibernateAdapter.<clinit>(HibernateUtil.java:13)
        at DataLayer.ApplicationDbContext.<init>(DatabaseContext.java:10)
        at ScanningServer.MainProg.init(TestMain.java:58)
        at ScanningServer.MainProg.main(TestMain.java:25)
        ... 5 more
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
        at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHe
lper.java:173)

buildSessionFactory():

private static SessionFactory buildSessionFactory() {
        Properties hibernateProperties = new Properties();
        Properties hib = new Properties();
        if (sessionFactory == null){
            try {
                hibernateProperties.load(HibernateUtil.class.getClassLoader().getSystemClassLoader()
                                                          .getResourceAsStream("hibernate.properties"));
                Configuration configuration = new Configuration().configure();
                serviceRegistry = new StandardServiceRegistryBuilder()
                        .applySettings(configuration.getProperties()).build();
                sessionFactory = configuration.addAnnotatedClass(Account.class)
                        .addAnnotatedClass(Consumer.class).addAnnotatedClass(Order.class)
                        .addAnnotatedClass(Customer.class)
                        .addAnnotatedClass(Products.class)
                        .addAnnotatedClass(Category.class)
                        .addAnnotatedClass(Schedules.class)
                        .addAnnotatedClass(Alert.class)
                        .mergeProperties(hibernateProperties)
                        .configure("hibernate.cfg.xml").buildSessionFactory(serviceRegistry);
            } catch (Exception e) {
                System.err.println("Initial SessionFactory creation failed." + e);
                throw new ExceptionInInitializerError(e);
            }
        }   
        return sessionFactory;
    }

hibernate.properties:

hibernate.connection.url=jdbc:mysql://localhost/MyProjectDB?createDatabaseIfNotExist=true
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.username=root
hibernate.connection.password=Admin123!

请帮助我克服这个!!

1 个答案:

答案 0 :(得分:0)

使用

URL input = HibernateUtil.class.getResource("hibernate.cfg.xml");  
configure(input).buildSessionFactory(serviceRegistry); 

抱歉试试这个

public class HibernateUtil {    

 private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {
     try {                       
         ClassLoader classLoader = HibernateUtil.class.getClassLoader();             
         File file = new File(classLoader.getResource("Hibernate.properties").getFile());                                           
         Properties hibernateProperties = new Properties();          
         hibernateProperties.load(new FileInputStream(file));                                           
         Configuration configuration = new Configuration();          
         configuration.configure("/resources/hibernate.cfg.xml");            
         configuration.addProperties(hibernateProperties);           
         configuration.addAnnotatedClass(User.class);                               
         StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());             
         SessionFactory sf = configuration.buildSessionFactory(builder.build());
         return sf;          
     } catch (Throwable ex) {
         ex.printStackTrace();
         System.err.println("SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);
     }
 }

 public static SessionFactory getSessionFactory() {
     return sessionFactory;
 }

 public static void shutdown() {
     // Close caches and connection pools
     getSessionFactory().close();
 }

}

  1. 我使用hibernate依赖创建了一个maven项目。
  2. 将项目导出为runnable jar文件,并选中“将所需的包打包到生成的jar”
  3. 使用“java -jar myjar.jar”
  4. 运行