Соединения не могут быть получены из базовой базы данных! - HSQL DB

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

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

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

При попытке запустить целевой schemaexport, я получаю сообщение об ошибке ниже.

schemaexport: [hibernatetool] Выполнение инструмента Hibernate со стандартной конфигурацией [hibernatetool] 1. task: hbm2ddl (Генерирует схему базы данных) [hibernatetool] 18:07:56,555 INFO Среда:500 - Hibernate 3.2.0.cr5 [hibernatetool] 18:07:56,555 INFO Среда:533 - hibernate.properties not fo und [hibernatetool] 18:07:56,555 INFO Среда:667 - Имя поставщика байт-кода: cg lib [hibernatetool] 18:07:56,571 INFO Среда:584 - с использованием JDK 1.4 java. Обработка меток времени [hibernatetool] 18:07:56,617 Конфигурация INFO:1384 - настройка из файла: h ibernate.cfg.xml [hibernatetool] 18:07:56,680 Конфигурация INFO:507 - Чтение сопоставлений из ресурса: привет / Сообщение.hbm.xml [hibernatetool] 18:07:56,758 ИНФОРМАЦИЯ HbmBinder:300 - Класс отображения: hello.Message -> СООБЩЕНИЯ [hibernatetool] 18:07:56,851 ИНФОРМАЦИЯ Конфигурация:1465 - Настроенный SessionFactor y: null [hibernatetool] 18:07:56 851 INFO Dialect:141 - Использование диалекта: org.hibernate.di alect.HSQLDialect [hibernatetool] 18:07:56 914 INFO SchemaExport:154 - Запуск схемы hbm2ddl exp ort [hibernatetool] 18:07:56 914 INFO SchemaExport:174 - запись сгенерированной схемы в файл: C:\Users\Ramesh\Desktop\ Учебники \hibernate\ Образцы кода Hibernate \jpwh- gettingstarted-070401\helloworld-native\helloworld-ddl.sql [hibernatetool] 18:07:56,914 INFO SchemaExport:179 - экспорт сгенерированной схемы в базу данных [hibernatetool] 18:07:56,914 INFO C3P0ConnectionProvider:50 - C3P0 с использованием драйвера: org.hsqldbver.jb по 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 - экспорт схемы не выполнен

[hibernatetool] java.sql.SQLException: Соединения не могут быть получены из базовой базы данных! [hibernatetool] по адресу com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.j ava:104) ] at com.mchange.v2.c3p0.PoolBackedDataSource.getConnectio n(PoolBackedDataSource.java:94) [hibernatetool] в org.hibernate.connection.C3P0ConnectionProvider.getCo nnection(C3P0ConnectionProvider.hiber.hiber:35).tool.hbm2ddl.ManagedProviderConnectionH elper.prepare(ManagedProviderConnectionHelper.java:28) [hibernatetool] в org.hibernate.tool.hbm2ddl.SchemaExport.execute(Schem aExport.java:180) [hibertool]
в org.hibernate.tool.hbm2ddl.SchemaExport.create(схема экспорта.java:133) [hibernatetool]
в org.hibernate.tool.ant.Hbm2DDLExporterTask.execute(Hb m2DDLExporterTask.java:55) [hibernatetool] в org.hibernate.tool.ant.HibernateToolTask.execute(Hibe rnateToolTastool))..tools.ant.UnknownElement.execute (UnknownEl ement.java:291) [hibernatetool]
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native M ethod) [hibernatetool] в sun.reflect.NativeMethodAccessorImpl.invoke(NativeMet hodAccessorImpl.java:39) [hibernatetoolj (ответ:) [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.perform(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 ject.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.CannotAcquireResourceExce ption: ResourcePool не удалось получить ресурс из своей первичной фабрики или источника. [Hibernatetool]
на com.mchange.v2.resourcepool.BasicResourcePool.awaitAc quire(BasicResourcePool.java:970) [hibernatetool] на com.mchange.v2.resourcepool.BasicResourcePool.checkou tResource(BasicResourcePool.java:208) [объект гибернации].v2.c3p0.impl.C3P0PooledConnectionPool.che ckoutPooledConnection(C3P0PooledConnectionPool.java:232) [hibernatetool] ... еще 24 [hibernatetool] 1 ошибки произошли во время выполнения. [hibernatetool] Ошибка № 1: java.sql.SQLException: Соединения не могут быть получены из базовой базы данных! [hibernatetool] 18:08:26,569 WARN BasicResourcePool:1222 - com.mchange.v2.resou rcepool.BasicResourcePool$AcquireTask@72f864fe - Ошибка попытки получения!!! Очистка в ожидании приобретений. Пытаясь получить необходимый новый ресурс, мы добились успеха, превышающего максимальное количество разрешенных попыток приобретения (30).

У меня не слишком много знаний о hiberate или HSQL..

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

Спасибо

РЕДАКТИРОВАТЬ: я пытаюсь запустить проект helloworld-native,

Цель, указанная в файле ant build.xml для 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>

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

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 DB только в режиме сервера (из вышеприведенного вывода)..

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

1 ответ

Решение

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

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

$ 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 schemaexport из другой оболочки:

$ 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

И действительно, когда работает ant dbmanagerЯ могу видеть MESSAGES стол, как и ожидалось.

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


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

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

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

Другие вопросы по тегам