problemas con hibernate

pelirroja
11 de Marzo del 2010
Hola, estoy intentando seguir el manual "Java Persistence with Hibernate", y me ha surgido un problema que no sé como solventar. Voy por el capítulo dos, intentando construir el build.xml, pero me dá un error. Dentro de eclipse, en el build.xml, una línea me dá un error de que no encuentra algo:

En la línea: <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="project.classpath"/>

me indica que: C:\Documents and Settings\empalacios\workspaceManningJP\HelloWorldJP\${lib.dir} not found.

y cuando limpio, compilo, y le doy a run, me salen varios errores, me faltan librerías que no aparecen en el manual, concretamente: slf4j-api-1.5.3.jar y slf4j-jdk14-1.4.2.jar. Las añado, y sigue dando los siguientes errores:

[mkdir] Created dir: C:\Documents and Settings\empalacios\workspaceManningJP\HelloWorldJP\bin
compile:
[javac] Compiling 3 source files to C:\Documents and Settings\empalacios\workspaceManningJP\HelloWorldJP\bin
copymetafiles:
[copy] Copying 1 file to C:\Documents and Settings\empalacios\workspaceManningJP\HelloWorldJP\bin
run:
[java] 04-mar-2010 16:50:41 org.hibernate.cfg.Environment <clinit>
[java] INFO: Hibernate 3.3.2.GA
[java] 04-mar-2010 16:50:41 org.hibernate.cfg.Environment <clinit>
[java] INFO: hibernate.properties not found
[java] 04-mar-2010 16:50:41 org.hibernate.cfg.Environment buildBytecodeProvider
[java] INFO: Bytecode provider name : javassist
[java] 04-mar-2010 16:50:41 org.hibernate.cfg.Environment <clinit>
[java] INFO: using JDK 1.4 java.sql.Timestamp handling
[java] 04-mar-2010 16:50:41 org.hibernate.cfg.Configuration configure
[java] INFO: configuring from resource: /hibernate.cfg.xml
[java] 04-mar-2010 16:50:41 org.hibernate.cfg.Configuration getConfigurationInputStream
[java] INFO: Configuration resource: /hibernate.cfg.xml
[java] Exception in thread "main" java.lang.ExceptionInInitializerError
[java] at persistence.HibernateUtil.<clinit>(Unknown Source)
[java] at hello.HelloWorld.main(Unknown Source)
[java] Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
[java] at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
[java] at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1453)
[java] at org.hibernate.cfg.Configuration.configure(Configuration.java:1475)
[java] at org.hibernate.cfg.Configuration.configure(Configuration.java:1462)
[java] ... 2 more
[java] Java Result: 1
BUILD SUCCESSFUL
Total time: 2 seconds

No lo entiendo, porque parece que me dice que no encuentra el archivo hibernate.cfg.xml, pero ese archivo le tengo. ¿Alguien le ha ocurrido lo mismo o algo parecido? Estoy estancada, no sé como continuar.
Gracias por todo, un saludo

pelirroja
11 de Marzo del 2010
Hola, he conseguido eliminar un error pero obtengo otro:

[quote]Buildfile: C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbuild.xml
clean:
[delete] Deleting directory C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbin
[mkdir] Created dir: C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbin
compile:
[javac] Compiling 3 source files to C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbin
copymetafiles:
[copy] Copying 2 files to C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbin
run:
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.Environment <clinit>
[java] INFO: Hibernate 3.3.2.GA
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.Environment <clinit>
[java] INFO: hibernate.properties not found
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.Environment buildBytecodeProvider
[java] INFO: Bytecode provider name : javassist
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.Environment <clinit>
[java] INFO: using JDK 1.4 java.sql.Timestamp handling
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.Configuration configure
[java] INFO: configuring from resource: /hibernate.cfg.xml
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.Configuration getConfigurationInputStream
[java] INFO: Configuration resource: /hibernate.cfg.xml
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.Configuration addResource
[java] INFO: Reading mappings from resource : hello/Message.hbm.xml
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
[java] INFO: Mapping class: hello.Message -> MESSAGES
[java] 05-mar-2010 13:47:29 org.hibernate.cfg.Configuration doConfigure
[java] INFO: Configured SessionFactory: null
[java] 05-mar-2010 13:47:29 org.hibernate.connection.DriverManagerConnectionProvider configure
[java] INFO: Using Hibernate built-in connection pool (not for production use!)
[java] 05-mar-2010 13:47:29 org.hibernate.connection.DriverManagerConnectionProvider configure
[java] INFO: Hibernate connection pool size: 20
[java] 05-mar-2010 13:47:29 org.hibernate.connection.DriverManagerConnectionProvider configure
[java] INFO: autocommit mode: false
[java] 05-mar-2010 13:47:29 org.hibernate.connection.DriverManagerConnectionProvider configure
[java] INFO: using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:hsql://localhost
[java] 05-mar-2010 13:47:29 org.hibernate.connection.DriverManagerConnectionProvider configure
[java] INFO: connection properties: {user=sa}
[java] 05-mar-2010 13:47:30 org.hibernate.cfg.SettingsFactory buildSettings
[java] ADVERTENCIA: Could not obtain connection to query metadata
[java] java.sql.SQLException: socket creation error
[java] at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
[java] at org.hsqldb.jdbc.jdbcConnection.<init>(Unknown Source)
[java] at org.hsqldb.jdbcDriver.getConnection(Unknown Source)
[java] at org.hsqldb.jdbcDriver.connect(Unknown Source)
[java] at java.sql.DriverManager.getConnection(Unknown Source)
[java] at java.sql.DriverManager.getConnection(Unknown Source)
[java] at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133)
[java] at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:111)
[java] at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2119)
[java] at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2115)
[java] at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1339)
[java] at persistence.HibernateUtil.<clinit>(Unknown Source)
[java] at hello.HelloWorld.main(Unknown Source)
[java] Exception in thread "main" java.lang.ExceptionInInitializerError
[java] at persistence.HibernateUtil.<clinit>(Unknown Source)
[java] at hello.HelloWorld.main(Unknown Source)
[java] Caused by: org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection avalable
[java] at org.hibernate.dialect.resolver.DialectFactory.buildDialect(DialectFactory.java:107)
[java] at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:134)
[java] at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2119)
[java] at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2115)
[java] at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1339)
[java] ... 2 more
[java] Java Result: 1
BUILD SUCCESSFUL
Total time: 3 seconds[/quote]

Entiendo que no conecta a la bbdd hsql por algún motivo, ¿podéis echarme un cable? Muchas gracias, un saludo

pelirroja
11 de Marzo del 2010
He seguido avanzando, y por lo que veo no me encuentra una tabla, o no puede obtener el valor inicial para el generador, y no encuentro nada en San Google. Aquí están mis archivos:

hibernate.cfg.xml
[CODE] <!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
org.hsqldb.jdbcDriver
</property>
<property name="hibernate.connection.url">
jdbc:hsqldb:hsql://localhost
</property>
<property name="hibernate.connection.username">
sa
</property>
<property name="hibernate.dialet">
org.hibernate.dialect.HSQLDialect
</property>

<!-- Usando la conexión de c3p0 -->
<!-- Valor mínimo de conexiones JDBC que C3PO puede mantener -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- Valor máximo de conexiones que el pool puede mantener, si se pasa, lanzará una excepcion -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- Periodo de tiempo después del cual la conexión será borrada -->
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_text_period">3000</property>



<!-- Para mostrar e imprimir SQL y stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>

<!-- lista de mapeo de documentos xml -->
<mapping resource="hello/Message.hbm.xml"/>
</session-factory>
</hibernate-configuration> [/CODE]


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

<!-- Este documento xml le dice a hibernate que establezca una relación de
persistencia entre la clase Message y la tabla MESSAGES, relacionando cada
campo, y generando el esquema de la bbdd -->
<hibernate-mapping>
<class name="hello.Message" table="MESSAGES" >
<!-- Para que no dé error al crear la etiqueta class, debe tener al menos
el parámetro id dentro de ella-->
<id name="id" column="MESSAGE_ID">
<generator class="increment" />
</id>
<property name="text" column="MESSAGE_TEXT"/>
<many-to-one name="nextMessage" cascade="all"
column="NEXT_MESSAGE-ID" foreign-key="FK_NEXT_MESSAGE"/>
</class>
</hibernate-mapping> [/CODE]


y build.xml
[CODE]
<project name="HelloWorldJP" default="compile" basedir=".">

<!-- Nombre y versión del proyecto-->
<property name="proj.name" value="HelloWorldJP"/>
<property name="proj.version" value="1.0"/>

<!-- Propiedades globales para este constructor -->
<property name="src.java.dir" value="src"/>
<property name="lib.dir" value="lib"/>
<property name="build.dir" value="bin"/>

<!-- Declaración del classpath -->
<path id="project.classpath">
<fileset dir="${lib.dir}">
<include name="**/*.jar"/>
<include name="**/*.zip"/>
</fileset>
</path>

<!-- Accesos directos útiles -->
<patternset id="meta.files">
<include name="**/*.xml"/>
<include name="**/*.properties"/>
</patternset>

<!-- Limpieza -->
<target name="clean">
<delete dir="${build.dir}"/>
<mkdir dir="${build.dir}"/>
</target>

<!-- Compilar las fuentes de java -->
<target name="compile" depends="clean">
<mkdir dir="${build.dir}"/>
<javac srcdir="${src.java.dir}" destdir="${build.dir}" nowarn="on">
<classpath refid="project.classpath"/>
</javac>
</target>

<!-- Copia de metadatos para construir el classpath -->
<target name="copymetafiles">
<copy todir="${build.dir}">
<fileset dir="${src.java.dir}">
<patternset refid="meta.files"/>
</fileset>
</copy>
</target>

<!-- Ejecutando HelloWorldJP -->
<target name="run" depends="compile, copymetafiles"
description="Build and run HelloWorldJP">
<java fork="true" classname="hello.HelloWorld"
classpathref="project.classpath">
<classpath path="${build.dir}"/>
</java>
</target>

<!-- Schema Export -->

<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="project.classpath"/>

<target name="schemaexport" depends="compile, copymetafiles"
description="Exports a generated schema to DB and file">
<hibernatetool destdir="${basedir}">
<classpath path="${build.dir}"/>
<configuration configurationfile = "${build.dir}/hibernate.cfg.xml"/>
<!-- El exportador es hbm2ddl. Si drop=true, las declaraciones drop de sql son generadas primero y todas las tablas y ctes que
existan seran borradas antes de eso. Si create=true, las declaraciones sql son creadas después, creando
todas las tablas y ctes. Si export=true, todas las declaraciones ddl son directamente ejecutadas en bbdd,
abriendo una conexion con la bbdd encontrada en el fichero de configuracion-->
<hbm2ddl drop="true" create="true" export="true"
outputfilename="helloworld-ddl.sql" delimiter=";" format="true"/>
</hibernatetool>
</target>

<target name="dbmanager" description="Start HSQLDB manager">
<java classname="org.hsqldb.util.DatabaseManagerSwing"
fork="yes" classpathref="project.classpath" failonerror="true">
<arg value="-url"/>
<arg value="jdbc:hsqldb:hsql://localhost/"/>
<arg value="-driver"/>
<arg value="org.hsqldb.jdbcDriver"/>
</java>
</target>

</project> [/CODE]


que creo son los más importantes. Y éste es el error:
...
[java] 09-mar-2010 9:47:51 org.hibernate.stat.StatisticsImpl logSummary
[java] INFO: query cache misses: 0
[java] 09-mar-2010 9:47:51 org.hibernate.stat.StatisticsImpl logSummary
[java] INFO: max query time: 0ms
[java] Hibernate:
[java] select
[java] max(MESSAGE_ID)
[java] from
[java] MESSAGES
[java] 09-mar-2010 9:47:52 org.hibernate.util.JDBCExceptionReporter logExceptions
[java] ADVERTENCIA: SQL Error: -22, SQLState: S0002
[java] 09-mar-2010 9:47:52 org.hibernate.util.JDBCExceptionReporter logExceptions
[java] GRAVE: Table not found in statement [select max(MESSAGE_ID) from MESSAGES]
[java] Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not fetch initial value for increment generator
[java] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
[java] at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
[java] at org.hibernate.id.IncrementGenerator.getNext(IncrementGenerator.java:131)
[java] at org.hibernate.id.IncrementGenerator.generate(IncrementGenerator.java:6
[java] at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)
[java] at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
[java] at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
[java] at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
[java] at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
[java] at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
[java] at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:563)
[java] at org.hibernate.impl.SessionImpl.save(SessionImpl.java:551)
[java] at org.hibernate.impl.SessionImpl.save(SessionImpl.java:547)
[java] at hello.HelloWorld.main(Unknown Source)
[java] Caused by: java.sql.SQLException: Table not found in statement [select max(MESSAGE_ID) from MESSAGES]
[java] at org.hsqldb.jdbc.Util.throwError(Unknown Source)
[java] at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(Unknown Source)
[java] at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
[java] at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:534)
[java] at org.hibernate.jdbc.AbstractBatcher.prepareSelectStatement(AbstractBatcher.java:145)
[java] at org.hibernate.id.IncrementGenerator.getNext(IncrementGenerator.java:107)
[java] ... 11 more
[java] Java Result: 1
BUILD SUCCESSFUL
Total time: 3 seconds

Si alguien puede echarme un cable, lo agradecería mucho. Un saludo

pelirroja
11 de Marzo del 2010
Increible pero cierto, al final el problema era ... ¡un guión! en el fichero Message.hgm.xml tenía puesto column="NEXT_MESSAGE-ID" en lugar de column="NEXT_MESSAGE_ID". Arreglado este error, me crea la tabla en la bbdd, pero no sé porqué no puedo acceder a ella. Y al echar a correr el schemaexport, no puede hacer bien el build y dá el siguiente error:

uildfile: C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbuild.xml
clean:
[delete] Deleting directory C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbin
[mkdir] Created dir: C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbin
compile:
[javac] Compiling 3 source files to C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbin
copymetafiles:
[copy] Copying 3 files to C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbin
schemaexport:
[hibernatetool] Executing Hibernate Tool with a Standard Configuration
[hibernatetool] 1. task: hbm2ddl (Generates database schema)
[hibernatetool] 09-mar-2010 16:25:37 org.hibernate.cfg.Environment <clinit>
[hibernatetool] INFO: Hibernate 3.3.2.GA
[hibernatetool] 09-mar-2010 16:25:37 org.hibernate.cfg.Environment <clinit>
[hibernatetool] INFO: hibernate.properties not found
[hibernatetool] 09-mar-2010 16:25:37 org.hibernate.cfg.Environment buildBytecodeProvider
[hibernatetool] INFO: Bytecode provider name : javassist
[hibernatetool] 09-mar-2010 16:25:37 org.hibernate.cfg.Environment <clinit>
[hibernatetool] INFO: using JDK 1.4 java.sql.Timestamp handling
[hibernatetool] 09-mar-2010 16:25:37 org.hibernate.cfg.Configuration configure
[hibernatetool] INFO: configuring from file: hibernate.cfg.xml
[hibernatetool] 09-mar-2010 16:25:37 org.hibernate.cfg.Configuration addResource
[hibernatetool] INFO: Reading mappings from resource : hello/Message.hbm.xml
[hibernatetool] 09-mar-2010 16:25:37 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
[hibernatetool] INFO: Mapping class: hello.Message -> MESSAGES
[hibernatetool] 09-mar-2010 16:25:38 org.hibernate.cfg.Configuration doConfigure
[hibernatetool] INFO: Configured SessionFactory: null
[hibernatetool] 16:25:38,384
[hibernatetool] An exception occurred while running exporter #2:hbm2ddl (Generates database schema)
[hibernatetool] To get the full stack trace run ant with -verbose
[hibernatetool] org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect.

BUILD FAILED
C:Documents and SettingsempalaciosworkspaceManningJPHelloWorldJPbuild.xml:64: org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect.

Total time: 2 seconds

¿Tiene alguien alguna idea de porqué?

Muchas gracias, un saludo

pelirroja
11 de Marzo del 2010
Hola, al final el último error es por un error de escritura (de éstos que lo tienes delante y no los ves), y es que en el hibernate.cfg.xml la línea

<property name="hibernate.dialet">

es errónea, falta una c a dialet, lo correcto es:

<property name="hibernate.dialect">

y de ahí el último error.

He compilado y ya va todo ok. Gracias de todos modos la ayuda recibida, un saludo