Не удалось получить соединения из базовой базы данных! БД HSQL

Я пытаюсь изучить Hibernate из Java Persistence с помощью hibernate Гэвина Кинга.

Я только что загрузил примеры, приведенные в книге, по этому адресу http://downloads.jboss.org/hibernate/caveatemptor/jpwh-gettingstarted-070401.zip

Я запустил базу данных HSQL с помощью ant startdb, и база данных успешно запустилась.

При попытке запустить целевой экспорт схемы я получаю следующую ошибку.

schemaexport: [hibernatetool] Запуск Hibernate Tool со стандартной конфигурацией [hibernatetool] 1. задача: hbm2ddl (генерирует схему базы данных) [hibernatetool] 18:07:56,555 INFO Environment:500 — Hibernate 3.2.0.cr5 [hibernatetool] 18:07 :56,555 INFO Environment:533 - hibernate.properties not und [hibernatetool] 18:07:56,555 INFO Environment:667 - Имя поставщика байт-кода: cg lib [hibernatetool] 18:07:56,571 INFO Environment:584 - использование JDK 1.4 java. Обработка отметок времени sql.Time [hibernatetool] 18:07:56,617 Конфигурация INFO:1384 — настройка из файла: h ibernate.cfg.xml [hibernatetool] 18:07:56,680 Конфигурация INFO:507 — Чтение сопоставлений из ресурсов: hello/Message .hbm.xml [hibernatetool] 18:07:56,758 INFO HbmBinder:300 — класс сопоставления: hello.Message -> MESSAGES [hibernatetool] 18:07:56,851 INFO Configuration: 1465 — Configured SessionFactor y: null [hibernatetool] 18:07 :56,851 ИНФОРМАЦИЯ Диалект:141 - Использование диалекта: org.hibernate. di alect.HSQLDialect [hibernatetool] 18:07:56,914 INFO SchemaExport:154 - Запуск экспорта схемы hbm2ddl [hibernatetool] 18:07:56,914 INFO SchemaExport:174 - Запись сгенерированной схемы в файл: C:\Users\Ramesh\Desktop\ Tutorials\hibernate\Hibernate Code examples\jpwh-getstarted-070401\helloworld-native\helloworld-ddl.sql [hibernatetool] 18:07:56,914 INFO SchemaExport:179 — экспорт сгенерированной схемы в базу данных [hibernatetool] 18:07:56,914 INFO C3P0ConnectionProvider:50 — C3P0 с использованием драйвера: org.hsqldb.jdbcDriver по URL-адресу: jdbc:hsqldb:hsql://localhost [hibernatetool] 18:07:56,914 INFO C3P0ConnectionProvider:51 — свойства подключения: {user=sa} [hibernatetool] 18:07:56,914 INFO C3P0ConnectionProvider:54 — режим автоматической фиксации: false [hibernatetool] 18:08:26,554 WARN BasicResourcePool:1222 — com.mchange.v2.resou rcepool.BasicResourcePool$AcquireTask@61f1680f — попытка получения не удалась!!! Очистка ожидающих приобретения. При попытке получить необходимый новый ресурс нам не удалось добиться успеха больше, чем максимально допустимое количество попыток получения (30). [hibernatetool] 18:08:26,554 ОШИБКА SchemaExport:202 - неудачный экспорт схемы

У меня нет слишком много знаний ни о спящем режиме, ни о HSQL.

Кто-нибудь объясните, что здесь не так??

Спасибо

EDIT: я пытаюсь запустить проект helloworld-native.

Цель, указанная в файле ant build.xml для startdb, выглядит следующим образом:

и когда я запускаю команду ant startdb, я вижу следующий вывод:

<!-- Start the HSQL DB server -->
<target name="startdb" description="Run HSQL database server with clean DB">
    <!-- Delete database files -->
    <delete dir="${database.dir}"/>
    <java classname="org.hsqldb.Server"
          fork="yes"
          classpathref="project.classpath"
          failonerror="true">
        <arg value="-database.0"/>
        <arg value="file:${database.dir}/db"/>
    </java>
</target>

Затем я думаю, что запускаю БД HSQL только в режиме сервера (из приведенного выше вывода).

startdb:
     [delete] Deleting directory C:\Users\Ramesh\Desktop\Tutorials\hibernate\Hibernate Code samples\jpwh-gettingstarted-070401\helloworld-native\database
     [java] [Server@15ded0fd]: [Thread[main,5,main]]: checkRunning(false) entered
     [java] [Server@15ded0fd]: [Thread[main,5,main]]: checkRunning(false) exited

     [java] [Server@15ded0fd]: Startup sequence initiated from main() method
     [java] [Server@15ded0fd]: Loaded properties from [C:\Users\Ramesh\Desktop\Tutorials hibernate\Hibernate Code samples\jpwh-gettingstarted-070401\helloworld-native\server.properties]
     [java] [Server@15ded0fd]: Initiating startup sequence...
     [java] [Server@15ded0fd]: Server socket opened successfully in 29 ms.
     [java] [Server@15ded0fd]: Database [index=0, id=0, db=file:database/db, alias=] opened sucessfully in 469 ms.
     [java] [Server@15ded0fd]: Startup sequence completed in 523 ms.
     [java] [Server@15ded0fd]: 2010-11-08 22:11:08.027 HSQLDB server 1.8.0 is online
     [java] [Server@15ded0fd]: To close normally, connect and execute SHUTDOWN SQL
     [java] [Server@15ded0fd]: From command line, use [Ctrl]+[C] to abort abruptly

Подскажите, что еще мне не хватает..

Обновление: при повторном рассмотрении оказывается, что я был неправ, вы можете запустить HSQL в режиме сервера с помощью ant-скрипта, и вам не обязательно использовать командную строку. На самом деле, я пытался воспроизвести проблему с образцом helloworld-native, но у меня это сработало.


person javanoob    schedule 07.11.2010    source источник
comment
Паскаль, я добавил комментарии к вопросу... Можете посмотреть, когда будет время.. Заранее спасибо..   -  person javanoob    schedule 07.11.2010


Ответы (1)


Сначала я запустил HSQLDB в первой оболочке, используя ant startdb:

Затем я запустил ant schemaexport из другой оболочки:

$ ant startdb 
Buildfile: /home/pascal/Projects/jpwh-gettingstarted-070401/helloworld-native/build.xml

startdb:
     [java] [Server@a97b0b]: [Thread[main,5,main]]: checkRunning(false) entered
     [java] [Server@a97b0b]: [Thread[main,5,main]]: checkRunning(false) exited
     [java] [Server@a97b0b]: Startup sequence initiated from main() method
     [java] [Server@a97b0b]: Loaded properties from [/home/pascal/Projects/jpwh-gettingstarted-070401/helloworld-native/server.properties]
     [java] [Server@a97b0b]: Initiating startup sequence...
     [java] [Server@a97b0b]: Server socket opened successfully in 39 ms.
     [java] [Server@a97b0b]: Database [index=0, id=0, db=file:database/db, alias=] opened sucessfully in 1148 ms.
     [java] [Server@a97b0b]: Startup sequence completed in 1281 ms.
     [java] [Server@a97b0b]: 2010-11-08 18:29:20.094 HSQLDB server 1.8.0 is online
     [java] [Server@a97b0b]: To close normally, connect and execute SHUTDOWN SQL
     [java] [Server@a97b0b]: From command line, use [Ctrl]+[C] to abort abruptly

И действительно, при запуске ant dbmanager я вижу таблицу MESSAGES, как и ожидалось.

$ ant schemaexport 
Buildfile: /home/pascal/Projects/jpwh-gettingstarted-070401/helloworld-native/build.xml

compile:
    [mkdir] Created dir: /home/pascal/Projects/jpwh-gettingstarted-070401/helloworld-native/build
    [javac] /home/pascal/Projects/jpwh-gettingstarted-070401/helloworld-native/build.xml:39: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 3 source files to /home/pascal/Projects/jpwh-gettingstarted-070401/helloworld-native/build

copymetafiles:
     [copy] Copying 3 files to /home/pascal/Projects/jpwh-gettingstarted-070401/helloworld-native/build

schemaexport:
[hibernatetool] Executing Hibernate Tool with a Standard Configuration
[hibernatetool] 1. task: hbm2ddl (Generates database schema)
[hibernatetool] 
[hibernatetool]     alter table MESSAGES 
[hibernatetool]         drop constraint FK_NEXT_MESSAGE;
[hibernatetool] 
[hibernatetool]     drop table MESSAGES if exists;
[hibernatetool] 
[hibernatetool]     create table MESSAGES (
[hibernatetool]         MESSAGE_ID bigint generated by default as identity (start with 1),
[hibernatetool]         MESSAGE_TEXT varchar(255),
[hibernatetool]         NEXT_MESSAGE_ID bigint,
[hibernatetool]         primary key (MESSAGE_ID)
[hibernatetool]     );
[hibernatetool] 
[hibernatetool]     alter table MESSAGES 
[hibernatetool]         add constraint FK_NEXT_MESSAGE 
[hibernatetool]         foreign key (NEXT_MESSAGE_ID) 
[hibernatetool]         references MESSAGES;
[hibernatetool] 1 errors occurred while performing <hbm2ddl>.
[hibernatetool] Error #1: java.sql.SQLException: Table not found: MESSAGES in statement [alter table MESSAGES]

BUILD SUCCESSFUL
Total time: 14 seconds

Так что все работало просто отлично, из коробки. Если это не для вас, возможно, начните искать такие вещи, как проблема с сетью, персональный брандмауэр и т. Д.

По трассировке похоже, что HSQL не запущен (по крайней мере, не в режиме сервера), и я подозреваю, что вы не запустили его так, как должны были. Чтобы запустить его в режиме сервера, из каталога helloworld-reverse запустите (как описано в разделе Запуск системы баз данных HSQL, стр. 98):


Затем вы сможете подключиться к нему, используя строку подключения jdbc:hsqldb:hsql://localhost.

$ java -cp lib/hsqldb.jar org.hsqldb.Server

Пробовал с mysql.. и он работает.. Не знаю, в чем проблема?

person Pascal Thivent    schedule 07.11.2010
comment
Спасибо, Паскаль... нашел время, чтобы посмотреть на мой вопрос... Как вы сказали, я думаю, что проблема может быть в сети.. Однако я могу продолжить работу с _1_ БД. Еще раз спасибо - person javanoob; 08.11.2010
comment
[hibernatetool] java.sql.SQLException: невозможно получить соединения из базовой базы данных! [hibernatetool] в com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.j ava:104) [hibernatetool] в com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.che ckoutPooledConnection(C3P0PooledConnectionPool.java:236) [hibernatetool ] в com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:94) [hibernatetool] в org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35) [hibernatetool] в org.hibernate. tool.hbm2ddl.ManagedProviderConnectionH elper.prepare(ManagedProviderConnectionHelper.java:28) [hibernatetool] в org.hibernate.tool.hbm2ddl.SchemaExport.execute(Schem aExport.java:180) [hibernatetool]
в org.hibernate.tool .hbm2ddl.SchemaExport.create(Schema Export.java:133) [hibernatetool]
в org.hibernate.tool.ant.Hbm2DDLExporterTask.execute(Hb m2DDLExporterTask.java:55) [hibernatetool] в org.hibernate.tool. муравей Хиберн ateToolTask.execute(Hibe rnateToolTask.java:171) [hibernatetool] в org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [hibernatetool]
в sun.reflect.NativeMethodAccessorImpl.invoke0(Native метод) [hibernatetool] в sun.reflect.NativeMethodAccessorImpl.invoke(NativeMet hodAccessorImpl.java:39) [hibernatetool] в sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [hibernatetool] в java.lang.reflect .Method.invoke(Method.java:597) [hibernatetool] в org.apache.tools.ant.dispatch.DispatchUtils.execute(D ispatchUtils.java:106) [hibernatetool] в org.apache.tools.ant.Task. выполнить (Task.java:348) [hibernatetool] в org.apache.tools.ant.Target.execute(Target.java:390) [hibernatetool] в org.apache.tools.ant.Target.performTasks(Target.java: 411) [hibernatetool] в org.apache.tools.ant.Project.executeSortedTargets(Pro jec t.java:1397) [hibernatetool]
в org.apache.tools.ant.Project.executeTarget(Project.ja va:1366) [hibernatetool] в org.apache.tools.ant.helper.DefaultExecutor.executeTa rgets (DefaultExecutor.java:41) [hibernatetool] в org.apache.tools.ant.Project.executeTargets(Project.j ava:1249) [hibernatetool] в org.apache.tools.ant. Main.runBuild(Main.java:801) [hibernatetool] в org.apache.tools.ant.Main.startAnt(Main.java:218) [hibernatetool] в org.apache.tools.ant.launch.Launcher.run( Launcher.jav a:280) [hibernatetool] в org.apache.tools.ant.launch.Launcher.main(Launcher.ja va:109) [hibernatetool] Причина: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool не удалось получить ресурс с его основной фабрики или источника. [hibernatetool]
на com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:970) [hibernatetool] на com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:208) [ hibernatetool] на com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:232) [hibernatetool] ... еще 24 [hibernatetool] 1 ошибка при выполнении . [hibernatetool] Ошибка № 1: java.sql.SQLException: невозможно получить соединения из базовой базы данных! [hibernatetool] 18:08:26,569 ПРЕДУПРЕЖДЕНИЕ BasicResourcePool:1222 - com.mchange.v2.resou rcepool.BasicResourcePool$AcquireTask@72f864fe -- Попытка получения не удалась!!! Очистка ожидающих приобретения. При попытке получить необходимый новый ресурс нам не удалось превысить максимально допустимое количество попыток получения (30) .` - person javanoob; 09.11.2010