Соединение БД с MySQL через Hibernate на Embedded Glassfish - PullRequest
0 голосов
/ 27 октября 2010

У меня проблема с подключением базы данных MySQL через Hibernate / JPA2 на встроенном Glassfish.

Моя среда:

  • Maven 2
  • Встроенный Glassfish (встроенный через плагин Maven)
  • Затмение + M2Plugin
  • Hibernate 3.5.6
  • MySQL (@localhost) (работает и может быть подключен без контейнера через Hibernate Sessionfactory)

Вот мой стек исключений во время загрузки встроенного Glassfish


27.10.2010 16:22:14 com.sun.enterprise.v3.server.AppServerStartup run
INFO: GlassFish v3 (74.2) startup time : Embedded(229ms) startup services(154ms) total(383ms)
27.10.2010 16:22:14 com.sun.enterprise.transaction.JavaEETransactionManagerSimplified initDelegates
INFO: Using com.sun.enterprise.transaction.jts.JavaEETransactionManagerJTSDelegate as the delegate
27.10.2010 16:22:14 org.glassfish.admin.mbeanserver.JMXStartupService$JMXConnectorsStarterThread run
INFO: JMXStartupService: JMXConnector system is disabled, skipping.
27.10.2010 16:22:14 AppServerStartup run
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
27.10.2010 16:22:14 org.hibernate.validator.util.Version 
INFO: Hibernate Validator null
27.10.2010 16:22:14 org.hibernate.validator.engine.resolver.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
27.10.2010 16:22:14 com.sun.enterprise.v3.services.impl.GrizzlyProxy$2$1 onReady
INFO: Grizzly Framework 1.9.18-k started in: 62ms listening on port 8090
27.10.2010 16:22:17 com.sun.enterprise.security.SecurityLifecycle 
INFO: security.secmgroff
27.10.2010 16:22:17 com.sun.enterprise.security.ssl.SSLUtils checkCertificateDates
SCHWERWIEGEND: java_security.expired_certificate
27.10.2010 16:22:17 com.sun.enterprise.security.SecurityLifecycle onInitialization
INFO: Security startup service called
27.10.2010 16:22:17 com.sun.enterprise.security.PolicyLoader loadPolicy
INFO: policy.loading
27.10.2010 16:22:17 com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: Realm admin-realm of classtype com.sun.enterprise.security.auth.realm.file.FileRealm successfully created.
27.10.2010 16:22:17 com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: Realm file of classtype com.sun.enterprise.security.auth.realm.file.FileRealm successfully created.
27.10.2010 16:22:17 com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: Realm certificate of classtype com.sun.enterprise.security.auth.realm.certificate.CertificateRealm successfully created.
27.10.2010 16:22:17 com.sun.enterprise.security.SecurityLifecycle onInitialization
INFO: Security service(s) started successfully....
27.10.2010 16:22:18 com.sun.common.util.logging.LoggingConfigImpl openPropFile
INFO: Cannot read logging.properties file. 
27.10.2010 16:22:18 com.sun.enterprise.web.WebContainer createHttpListener
INFO: Created HTTP listener embedded-listener on port 8090
27.10.2010 16:22:18 com.sun.enterprise.web.WebContainer createHosts
INFO: Created virtual server server
27.10.2010 16:22:18 com.sun.enterprise.web.WebContainer loadSystemDefaultWebModules
INFO: Virtual server server loaded system default web module
27.10.2010 16:22:20 org.hibernate.validator.engine.resolver.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
27.10.2010 16:22:20 org.hibernate.cfg.annotations.Version 
INFO: Hibernate Annotations 3.5.6-Final
27.10.2010 16:22:20 org.hibernate.cfg.Environment 
INFO: Hibernate 3.5.6-Final
27.10.2010 16:22:20 org.hibernate.cfg.Environment 
INFO: hibernate.properties not found
27.10.2010 16:22:20 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : javassist
27.10.2010 16:22:20 org.hibernate.cfg.Environment 
INFO: using JDK 1.4 java.sql.Timestamp handling
27.10.2010 16:22:20 org.hibernate.annotations.common.Version 
INFO: Hibernate Commons Annotations 3.2.0.Final
27.10.2010 16:22:20 org.hibernate.ejb.Version 
INFO: Hibernate EntityManager 3.5.6-Final
27.10.2010 16:22:20 org.hibernate.ejb.Ejb3Configuration configure
INFO: Processing PersistenceUnitInfo [
    name: workbench
    ...]
27.10.2010 16:22:21 org.hibernate.ejb.Ejb3Configuration prepareProperties
WARNUNG: Defining hibernate.transaction.flush_before_completion=true ignored in HEM
27.10.2010 16:22:21 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: com.pentasys.workbench.db.model.User
27.10.2010 16:22:21 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity com.pentasys.workbench.db.model.User on table User
27.10.2010 16:22:21 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: com.pentasys.workbench.db.model.base.ATask
27.10.2010 16:22:21 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity com.pentasys.workbench.db.model.base.ATask on table JOB
27.10.2010 16:22:21 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: com.pentasys.workbench.db.model.Job
27.10.2010 16:22:21 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: com.pentasys.workbench.db.model.Comment
27.10.2010 16:22:21 org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity com.pentasys.workbench.db.model.Comment on table COMMENT
27.10.2010 16:22:21 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: com.pentasys.workbench.db.model.Workflow
27.10.2010 16:22:21 org.hibernate.cfg.annotations.CollectionBinder bindOneToManySecondPass
INFO: Mapping collection: com.pentasys.workbench.db.model.base.ATask.childTasks -> JOB
27.10.2010 16:22:21 org.hibernate.cfg.AnnotationConfiguration applyHibernateValidatorLegacyConstraintsOnDDL
INFO: Hibernate Validator not found: ignoring
27.10.2010 16:22:21 org.hibernate.validator.engine.resolver.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
27.10.2010 16:22:21 org.hibernate.validator.engine.resolver.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
27.10.2010 16:22:21 org.hibernate.cfg.search.HibernateSearchEventListenerRegister enableHibernateSearch
INFO: Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
27.10.2010 16:22:21 org.hibernate.validator.engine.resolver.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
27.10.2010 16:22:21 org.hibernate.connection.ConnectionProviderFactory initializeConnectionProviderFromConfig
INFO: Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
27.10.2010 16:22:21 org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider configure
INFO: Using provided datasource
27.10.2010 16:22:21 com.sun.enterprise.resource.allocator.LocalTxConnectorAllocator createResource
WARNUNG: poolmgr.create_resource_error
27.10.2010 16:22:21 com.sun.enterprise.connectors.ConnectionManagerImpl internalGetConnection
WARNUNG: poolmgr.get_connection_failure
27.10.2010 16:22:21 com.sun.gjc.spi.base.DataSource getConnection
WARNUNG: jdbc.exc_get_conn
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
WARNUNG: Could not obtain connection to query metadata
java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Unknown database 'workbench'
    at com.sun.gjc.spi.base.DataSource.getConnection(DataSource.java:133)
    at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:68)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:114)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2163)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2159)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1383)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:892)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
    at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:181)
    at org.glassfish.persistence.jpa.PersistenceUnitLoader.(PersistenceUnitLoader.java:96)
    at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:121)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:644)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:296)
    at org.glassfish.kernel.embedded.EmbeddedDeployerImpl.deploy(EmbeddedDeployerImpl.java:214)
    at org.glassfish.kernel.embedded.EmbeddedDeployerImpl.deploy(EmbeddedDeployerImpl.java:144)
    at org.glassfish.maven.RunMojo.execute(RunMojo.java:105)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:569)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:539)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
    at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
    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:597)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
27.10.2010 16:22:21 org.hibernate.dialect.Dialect 
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
27.10.2010 16:22:21 org.hibernate.engine.jdbc.JdbcSupportLoader useContextualLobCreation
INFO: Disabling contextual LOB creation as connection was null
27.10.2010 16:22:21 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Transaction strategy: org.hibernate.ejb.transaction.JoinableCMTTransactionFactory
27.10.2010 16:22:21 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: instantiating TransactionManagerLookup: org.hibernate.transaction.SunONETransactionManagerLookup
27.10.2010 16:22:21 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: instantiated TransactionManagerLookup
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL inserts for batching: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
27.10.2010 16:22:21 org.hibernate.hql.ast.ASTQueryTranslatorFactory 
INFO: Using ASTQueryTranslatorFactory
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: enabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory createRegionFactory
INFO: Cache region factory : org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
27.10.2010 16:22:21 org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge 
INFO: Cache provider: org.hibernate.cache.HashtableCacheProvider
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Named query checking : enabled
27.10.2010 16:22:21 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Check Nullability in Core (should be disabled when Bean Validation is on): disabled
27.10.2010 16:22:21 org.hibernate.impl.SessionFactoryImpl 
INFO: building session factory

мой persistence.xml

[...]
<persistence-unit name="workbench" >
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
  <jta-data-source>jdbc/__default</jta-data-source>

    <class>com.pentasys.workbench.db.model.User</class>
    <class>com.pentasys.workbench.db.model.Job</class>
    <class>com.pentasys.workbench.db.model.Comment</class>
    <class>com.pentasys.workbench.db.model.Workflow</class>
    <class>com.pentasys.workbench.db.model.base.ATask</class>

  <properties>
     <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
     <property name="hibernate.show_sql" value="true"/>
     <property name="hibernate.transaction.flush_before_completion" value="true"/>
     <property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
     <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>

    <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
    <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/workbench"/>
    <property name="hibernate.connection.username" value="root"/>
    <property name="hibernate.connection.password" value="cannabis"/>

    <property name="hibernate.show_sql" value="true"/>


    <property name="hibernate.hbm2ddl.auto" value="alter"/>
  </properties>
</persistence-unit>

pom.xml - конфиг maven-plugin (встроенный glassfish)

[...]
    <plugin>
        <groupId>org.glassfish</groupId>
        <artifactId>maven-embedded-glassfish-plugin</artifactId>
        <version>3.0</version>
        <configuration>
            <goalPrefix>glassfish</goalPrefix>
            <app>${project.build.directory}/${project.build.finalName}.war</app>
            <port>8090</port>
            <contextRoot>workbench</contextRoot>
            <instanceRoot>${project.build.directory}/gfe-${maven.build.timestamp}</instanceRoot>            
            <autoDelete>true</autoDelete>
            <configFile>${basedir}/domain.xml</configFile>
        </configuration>
        <executions>
            <execution>
                <phase>install</phase>
                <goals>
                    <goal>run</goal>
                </goals>
            </execution>
        </executions>

domain.xml - конфигурация встраиваемой стеклянной рыбы

[...]
<resources>
    <jdbc-resource pool-name="__TimerPool" jndi-name="jdbc/__TimerPool" object-type="system-admin" />
    <jdbc-resource pool-name="MYSQLPool" jndi-name="jdbc/__default" />
    <jdbc-resource pool-name="H2TestPool" jndi-name="${testDatabaseDataSourceName}" />
    <jdbc-connection-pool name="__TimerPool" datasource-classname="org.apache.derby.jdbc.EmbeddedXADataSource" res-type="javax.sql.XADataSource">
      <property value="${com.sun.aas.instanceRoot}/lib/databases/ejbtimer" name="databaseName" />
      <property value=";create=true" name="connectionAttributes" />
    </jdbc-connection-pool>
    <jdbc-connection-pool is-isolation-level-guaranteed="false" name="MYSQLPool" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" res-type="javax.sql.DataSource">
      <property value="3306" name="port" />
      <property value="test" name="password" />
      <property value="root" name="user" />
      <property value="localhost" name="hostName" />
      <property value="workbench" name="databaseName" />
      <property value="jdbc:mysql://localhost:3306/workbench" name="url" />
      <property value=";alter=true" name="connectionAttributes" />
    </jdbc-connection-pool>
[...]

спасибо за совет!

1 Ответ

1 голос
/ 28 октября 2010

Я не могу обнаружить очевидную ошибку в ваших настройках GlassFish. FWIW, вот аналогичная конфигурация, которую я использую для подключения к MySQL, которая работает :

<domain>
  ...
  <resources>
    ...
    <jdbc-resource pool-name="PetcatalogPool" jndi-name="jdbc/petcatalog"/>
    <jdbc-connection-pool datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" res-type="javax.sql.DataSource" name="PetcatalogPool">
      <property name="DatabaseName" value="petcatalog"/>
      <property name="Password" value="petcatalog"/>
      <property name="Url" value="jdbc:mysql://localhost:3306/petcatalog"/>
      <property name="User" value="petcatalog"/>
    </jdbc-connection-pool>
    ...
  </resources>
  ...
</domain>

Я не уверен, что это поможет. Если это не так:

  • убедитесь, что вы можете подключиться к базе данных workbench с помощью клиента JDBC (Eclipse, SquirelSQL)
  • сначала убедитесь, что пул работает под GlassFish, т.е. убедитесь, что вы можете "пинговать" пул из консоли администратора (активируйте ведение журнала GlassFish, если требуется отладка).
  • затем добавьте Hibernate в смесь.
...