Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Общие вопросы > не работает пример HIBERNATE


Автор: ylims 6.7.2007, 08:28
имееем  следующую структуру:
              [src]
                |
                +--[ru]
                |     |
                |     +--[selfexpression]
                |               |
                |               +-hibernate.cfg.xml
                |               +-User.java
                |               +-User.hbm.xml
                |                        
                +--[test]
                      |
                      +-test.java

hibernate.cfg.xml
Код

<?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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.firebirdsql.jdbc.FBDriver</property>
        <property name="connection.url">jdbc:firebirdsql:localhost:C:\data\db\myProject.fdb</property>
        
<property name="connection.username">sysdba</property>
        <property name="connection.password">masterkey</property>

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

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.FirebirdDialect</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">create</property>

        <mapping resource="ru/selfexpression/User.hbm.xml"/>

    </session-factory>

</hibernate-configuration>


User.java
Код

package ru.selfexpression;

import java.util.Date;

public class User {
    private int id;
    private String name;
    private String pass;

    public User() {

    }
    public void setId(int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    public String getPass() {
        return pass;
    }



User.hbm.xml
Код

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="ru.selfexpression.User" table="USER">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" not-null="true" sql-type="VARCHAR" />
        </property>
        <property name="pass" type="java.lang.String">
            <column name="pass" not-null="true" sql-type="VARCHAR" />
        </property>
     </class>
</hibernate-mapping>


Test.java
Код

package ru.selfexpression.test;
import ru.selfexpression.Infinite;
import ru.selfexpression.User;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.io.File;

class Test {
    public static void main(String args[]) {
        try {
            User user = new User();
           /*user.setId(1);*/ user.setName("user"); user.setPass("qwerty");
            Configuration conf = new Configuration();

            //conf.configure("/ru/selfexpression/User.hbm.xml");
            conf.configure("/ru/selfexpression/hibernate.cfg.xml");

            SessionFactory sessionFactory = conf.buildSessionFactory();

            Session session = sessionFactory.getCurrentSession();
            Transaction t = session.beginTransaction();
            session.save(user);
            t.commit();
            sessionFactory.close();

        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
 }
   }
}



пытаюсь просто запустить тестовый примерчик, и вот что получаю:
Код

Exception in thread "main" java.lang.ExceptionInInitializerError
    at ru.selfexpression.test.Test.main(Test.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78)
Caused by: java.lang.NullPointerException
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1526)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1505)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
    at ru.selfexpression.test.Test.main(Test.java:21)
    ... 5 more

Process finished with exit code 1


прошу помощи,  smile , плиз хелп 
               

Автор: tux 6.7.2007, 08:49
Убери строку
Код

conf.configure("/ru/selfexpression/User.hbm.xml");

Автор: ylims 6.7.2007, 09:06
сделал. Теперь ругается:
Код

Exception in thread "main" java.lang.ExceptionInInitializerError
    at ru.selfexpression.test.Test.main(Test.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78)
Caused by: org.hibernate.MappingNotFoundException: resource: /ru/selfexpression/User.hbm.xml not found
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:563)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1584)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1552)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1531)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1505)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
    at ru.selfexpression.test.Test.main(Test.java:24)
    ... 5 more

Process finished with exit code 1


 мне кажется чот не так я делаю в hibernete.cfg.xml 
        вот это правильно? 
Код
<mapping resource="/ru/selfexpression/User.hbm.xml"/>



Автор: Alita 6.7.2007, 09:07
Попробуй изменить URL к базе и mapping resource следующим образом:
Код

<?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="connection.url">jdbc:firebirdsql:localhost:C:\data\db\myProject.fdb</property>
       .....................................
       <mapping resource="ru/selfexpression/User.hbm.xml"/>    
    </session-factory>    
</hibernate-configuration>


и в самом коде необязательно указывать путь к конфигурационному файлу, достаточно его положить в корень приложения - у тебя это будет папка src, а не selfexpression.
Код

SessionFactory sessionFactory = cfg.configure().buildSessionFactory();
 
И тем более не нужно указвать файл маппинга для загрузки в коде, как сказал tux, если он у тебя уже прописан в hibernate.cfg.xml.

Автор: tux 6.7.2007, 09:10
Цитата(ylims @  6.7.2007,  09:06 Найти цитируемый пост)
вот это правильно? 

Попробуй так:
Код

<mapping resource="ru/selfexpression/User.hbm.xml"/>

Автор: ylims 6.7.2007, 09:39
исправил всё (помечено жёлтеньким в посте №1). 
ещё не работает но уже ругается ближе к правде  smile , а именно:
Код

Hibernate: select gen_id( hibernate_sequence, 1 ) from RDB$DATABASE
Hibernate: insert into USER (name, pass, id) values (?, ?, ?)
Exception in thread "main" java.lang.ExceptionInInitializerError
    at ru.selfexpression.test.Test.main(Test.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78)
Caused by: org.hibernate.exception.GenericJDBCException: could not insert: [ru.selfexpression.User]
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2217)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2610)
    at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:52)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:232)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
    at ru.selfexpression.test.Test.main(Test.java:31)
    ... 5 more
Caused by: org.firebirdsql.jdbc.FBSQLException: GDS Exception. Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, char 13
USER
    at org.firebirdsql.jdbc.FBPreparedStatement.<init>(FBPreparedStatement.java:82)
    at org.firebirdsql.jdbc.FBConnection.prepareStatement(FBConnection.java:244)
    at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:497)
    at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:94)
    at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:87)
    at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:218)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2174)
    ... 16 more

Process finished with exit code 1

помогите сделать последний штрих 

Автор: Alita 6.7.2007, 10:03
ложишь Hibernate.cfg.xml в корень проекта (у тебя папка src) и в коде меняешь
Код

 conf.configure("/ru/selfexpression/hibernate.cfg.xml");
 SessionFactory sessionFactory = conf.buildSessionFactory();

на
Код

SessionFactory sessionFactory = conf.configure().buildSessionFactory();
.
User.hbm.xml должен быть в [selfexpression].

Либо, оставив Hibernate.cfg.xml в  [selfexpression]  попробуй в конфигурации указать
Код

<mapping resource=User.hbm.xml"/>

При чем в последнем уверенности нет.  smile 

Автор: ylims 6.7.2007, 10:09
Цитата(Alita @ 6.7.2007,  10:03)
ложишь Hibernate.cfg.xml в корень проекта (у тебя папка src) и в коде меняешь
Код

 conf.configure("/ru/selfexpression/hibernate.cfg.xml");
 SessionFactory sessionFactory = conf.buildSessionFactory();

на
Код

SessionFactory sessionFactory = conf.configure().buildSessionFactory();
.
User.hbm.xml должен быть в [selfexpression].

Либо, оставив Hibernate.cfg.xml в  [selfexpression]  попробуй в конфигурации указать
Код

<mapping resource=User.hbm.xml"/>

При чем в последнем уверенности нет.  smile

Alita да с етим вродь разобрался, теперь др проьлем  smile см мой отредактированный пост выше

Автор: fixxer 6.7.2007, 11:48
Табличка USER-то есть в базе? Если есть попробуйте обозвать по-другому, возможно конфликт со служебным словом.

Автор: ylims 9.7.2007, 03:59
благодарю за помощь, всё исправил, заработало  smile 

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