hibernate.cfg.xml не найден

Я новичок в Hibernate, читал эту книгу «Сохранение Java с Hibernate» и пытаюсь реализовать этот пример оттуда. Пока моя сборка Ant прошла успешно, но когда я пытаюсь выполнить класс, содержащий основной метод, я получаю следующее сообщение об ошибке:

19-Nov-2011 18:40:09 org.hibernate.cfg.Environment 
INFO: Hibernate 3.2.3
19-Nov-2011 18:40:09 org.hibernate.cfg.Environment 
INFO: hibernate.properties not found
19-Nov-2011 18:40:09 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
19-Nov-2011 18:40:09 org.hibernate.cfg.Environment 
INFO: using JDK 1.4 java.sql.Timestamp handling
19-Nov-2011 18:40:09 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
19-Nov-2011 18:40:09 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
    at persistence.HibernateUtil.(Unknown Source)
    at hello.Driver.main(Unknown Source)
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
    ... 2 more

Ясно, что спящий режим не может найти мой файл конфигурации, который находится в корневом каталоге. .

Проект

+lib

+src
  +hello
    HelloWorld.java
    Message.java
    message.hbm.xml
  +persistence
    HibernateUtil.java
build.xml
hibernate.cfg.xml

Мой полный исходный код можно найти здесь: http://pastebin.com/bGDUrxUf

У меня есть работающий сервер MySQL с базой данных hibernateapp и табличными сообщениями

Спасибо: )

14
задан greenLizard 19 November 2011 в 18:47
поделиться

1 ответ

Конфигурационный XML-файл, как по умолчанию ожидают, будет в корне Вашего CLASSPATH.

Вы можете выбрать другой XML или использование конфигурационного файла пути:

        SessionFactory sessionFactory;
        try {
            Logger log = Logger.getLogger(LOG);
            final String HIB_CONFIG = "/path/to/hibernate.cfg.xml";

            final File hibernate = new File(HIB_CONFIG);
            log.info("Try to init SessionFactory: " + HIB_CONFIG);

            // Create the SessionFactory from hibernate.cfg.xml
            if (hibernate.exists()) {
                log.info("File exists. Init with custom file.");
                sessionFactory = new Configuration()
                        .configure(hibernate)
                        .buildSessionFactory();
            } else {
                log.info("File doesn't exist. Init with default project file.");
                sessionFactory = new Configuration().configure().buildSessionFactory();
            }
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }

Для получения дополнительных сведений смотрят конфигурация сессии

0
ответ дан 1 December 2019 в 06:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: