Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java tools & IDE's > Hibernate+mySQL


Автор: Сонечка 21.10.2011, 14:00
Здравствуйте все!

У меня вылетает Exception при попытке подключиться к MySQL.
Собственно логи:
 
Код


Connected to the target VM, address: '127.0.0.1:1223', transport: 'socket'
!1121.10.2011 14:17:40 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.1.1
21.10.2011 14:17:45 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
21.10.2011 14:17:46 org.hibernate.cfg.Environment <clinit>
INFO: using CGLIB reflection optimizer
21.10.2011 14:17:46 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
21.10.2011 14:17:48 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: C:/Documents and Settings/EZatonskaya/ChemistryProject/out/production/ChemistryProject/hibernate.cfg.xml
21.10.2011 14:17:48 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: C:/Documents and Settings/EZatonskaya/ChemistryProject/out/production/ChemistryProject/hibernate.cfg.xml
!22org.hibernate.HibernateException: C:/Documents and Settings/EZatonskaya/ChemistryProject/out/production/ChemistryProject/hibernate.cfg.xml not found
    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1275)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1297)
    at DbConnection.main(DbConnection.java:16)
Disconnected from the target VM, address: '127.0.0.1:1223', transport: 'socket'

Process finished with exit code 0



Подскажите плизз, в чем проблема может быть?

Автор: AntonSaburov 21.10.2011, 14:13
Ошибка возможно в том, что 
C:/Documents and Settings/EZatonskaya/ChemistryProject/out/production/ChemistryProject/hibernate.cfg.xml  not found

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

Вот тут есть примеры - http://java-course.ru/students/students.php?name=part16

Автор: Сонечка 21.10.2011, 14:24
Цитата(AntonSaburov @ 21.10.2011,  14:13)
Ошибка возможно в том, что 
C:/Documents and Settings/EZatonskaya/ChemistryProject/out/production/ChemistryProject/hibernate.cfg.xml  not found

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

Вот тут есть примеры - http://java-course.ru/students/students.php?name=part16

Ну он там есть(
Исходники:
Код

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DbConnection {
    public static void main(String[] args) {
        StateTable ostates = new StateTable("Europ","Austria",1);
        Session session = null;
        Transaction t=null;

        try {
        // открываем hibernate сессию
        // при этом читается файл конфигурации
            System.out.print("!11");
        SessionFactory sessionFactory = new Configuration().configure("C:/Documents and Settings/EZatonskaya/ChemistryProject/out/production/ChemistryProject/hibernate.cfg.xml").buildSessionFactory();

            session = sessionFactory.openSession();

        // вставка записи
        t = session.beginTransaction();
        session.save(ostates);
        t.commit();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("!22");
        } finally {
        if (session != null) {
            System.out.print("!33");
            session.flush();
            session.close();
            }
        }
    }
}


Злосчастный C:/Documents and Settings/EZatonskaya/ChemistryProject/out/production/ChemistryProject/hibernate.cfg.xml
Код

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
   <property name="hibernate.connection.driver_class">
      com.mysql.jdbc.Driver
   </property>
   
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/hr
   </property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.password">1234</property>
   <property name="hibernate.connection.pool_size">10</property>
   <property name="show_sql">true</property>
   <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
   <property name="hibernate.hbm2ddl.auto">update</property>
 
   <mapping resource="ostates.hbm.xml"/>
</session-factory>
</hibernate-configuration>



Автор: LSD 21.10.2011, 15:31
Configuration().configure(String) пытается загрузить конфигурацию из classpath а не из файла.

Т.е. или положи hibernate.cfg.xml в classpath и вызывай 
Код

new Configuration.configure();

или:
Код

new Configuration.configure(new File("C:/Documents and Settings/...."));

Автор: sergioK1 29.12.2011, 09:25
Cонечка , ворос актуален??  самый простой (тупой способ) - кладешь свой файл во все папки , потом из каждой по очереди убираешь и смотришь когда работает , и когда нет,
 за все про все минут 5-10 требуеться , вообще ничего знать не нужно , метод  научного тыка  smile ,кустарно - но работает ,

LSD - не надо в classpath в нем и так много всего  ( ну и  защита от дураков  smile ). лучше в папочку отдельную, дедовский/майфрайновский способ
  так проще ,  

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)