Настройка базы данных MySQL с использованием Grail 2.4.4 (невозможно создать начальные подключения пула)

Я действительно новичок в технологии Grails. Я установил IDE Groovy/Grails Tool Suite™ (GGTS, Grails 2.4.4) для 64-разрядной версии Windows.

Путь среды был правильно обновлен в отношении JDK и Grails.

Я создал новый проект под названием «тест», добавил новый класс домена под названием «test.User» следующим образом:

package test

class User {

    Integer id
    String firstName
    String lastName

    static constraints = {
        id(blank:false, unique:true)
        firstName(blank:false)
        lastName(blank:false)
    }
}

применил статический каркас для создания соответствующего UserController и представлений, связанных с действиями CRUD.

Чтобы проверить, работает ли моя модель данных с базой данных H2, я сделал несколько обновлений в файле DataSource.groovy, и он работает: я добавил нового пользователя, чтобы запустить приложение, и когда я запускаю команду SELECT* в моей таблице USER (используя Grails dbconsole), и у меня отображается моя новая запись пользователя. Так что пока здесь все ок!

Но теперь я хочу подключить свое приложение к альтернативной базе данных SQL, используя другой коннектор JDBC. Я выбрал (ради совместимости) вариант, предложенный в моем файле BuildConfig.groovy, и раскомментировал его:

runtime mysql:mysql-connector-java:5.1.29

Когда я запускаю приложение «run-app» (по умолчанию я думаю, что мы находимся в среде разработки), я заметил, что зависимость mysql-connector-java-5.1.29.jar была добавлена ​​в мой каталог .m2 (C:\Users\ my_user_name.m2\repository\mysql\mysql-connector-java\5.1.29). Поэтому я думаю, что зависимость правильно зарегистрирована в каком-то файле MAVEN в Grails. Однако файл не отображается в каталоге ivy-cache. Это нормально?

Содержимое моего файла BuildConfig.groovy:

grails.servlet.version = "3.0" // Change depending on target container compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.work.dir = "target/work"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"

grails.project.fork = [
    // configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
    //  compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],

    // configure settings for the test-app JVM, uses the daemon by default
    test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
    // configure settings for the run-app JVM
    run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
    // configure settings for the run-war JVM
    war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
    // configure settings for the Console UI JVM
    console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]
]

grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {
        // specify dependency exclusions here; for example, uncomment this to disable ehcache:
        // excludes 'ehcache'
    }
    log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    checksums true // Whether to verify checksums on resolve
    legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility

    repositories {
        inherits true // Whether to inherit repository definitions from plugins

        grailsPlugins()
        grailsHome()
        mavenLocal()
        grailsCentral()
        mavenCentral()
        // uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
        //mavenRepo "http://repository.codehaus.org"
        //mavenRepo "http://download.java.net/maven/2/"
        //mavenRepo "http://repository.jboss.com/maven2/"
    }

    dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
        runtime 'mysql:mysql-connector-java:5.1.29'
        // runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
        //test "org.grails:grails-datastore-test-support:1.0.2-grails-2.4"
    }

    plugins {
        // plugins for the build system only
        build ":tomcat:7.0.55"

        // plugins for the compile step
        compile ":scaffolding:2.1.2"
        compile ':cache:1.1.8'
        compile ":asset-pipeline:1.9.9"

        // plugins needed at runtime but not for compilation
        runtime ":hibernate4:4.3.6.1" // or ":hibernate:3.6.10.18"
        runtime ":database-migration:1.4.0"
        runtime ":jquery:1.11.1"

        // Uncomment these to enable additional asset-pipeline capabilities
        //compile ":sass-asset-pipeline:1.9.0"
        //compile ":less-asset-pipeline:1.10.0"
        //compile ":coffee-asset-pipeline:1.8.0"
        //compile ":handlebars-asset-pipeline:1.3.0.3"
    }
}

Что касается файла DataSource.groovy, я заменил строку, касающуюся имени драйвера:

driverClassName = "org.h2.Driver"

by

driverClassName = "com.mysql.jdbc.Driver"

и для каждой среды (я знаю, что использую только среду разработки, но просто чтобы избежать некоторых ошибок) я заменил следующие строки:

url = "jdbc:h2:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"

by

url = "jdbc:mysql://localhost/test"

Я также добавил чуть ниже имя пользователя и пароль по умолчанию (как пользователь root) + имя класса драйвера, как показано ниже (снова для каждой среды):

driverClassName = "com.mysql.jdbc.Driver"
username = "root"
password = ""

Вот содержимое моего файла DataSource.groovy:

dataSource {
    pooled = true
    jmxExport = true
    //driverClassName = "org.h2.Driver"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "sa"
    password = ""
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
//    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
    cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
    singleSession = true // configure OSIV singleSession mode
    flush.mode = 'manual' // OSIV session flush mode outside of transactional context
}

// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
            //url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
            url = "jdbc:mysql://localhost/test"
            driverClassName = "com.mysql.jdbc.Driver"
            username = "root"
            password = ""
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            //url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
            url = "jdbc:mysql://localhost/test"
            driverClassName = "com.mysql.jdbc.Driver"
            username = "root"
            password = ""
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            //url = "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
            url = "jdbc:mysql://localhost/test"
            driverClassName = "com.mysql.jdbc.Driver"
            username = "root"
            password = ""
            properties {
               // See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
               jmxEnabled = true
               initialSize = 5
               maxActive = 50
               minIdle = 5
               maxIdle = 25
               maxWait = 10000
               maxAge = 10 * 60000
               timeBetweenEvictionRunsMillis = 5000
               minEvictableIdleTimeMillis = 60000
               validationQuery = "SELECT 1"
               validationQueryTimeout = 3
               validationInterval = 15000
               testOnBorrow = true
               testWhileIdle = true
               testOnReturn = false
               jdbcInterceptors = "ConnectionState"
               defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
            }
        }
    }
}

Теперь, когда я запускаю приложение, у меня возникает следующая ошибка:

ERROR pool.ConnectionPool  - Unable to create initial connections of pool.

Вот весь стек ошибок:

2016-08-23 16:18:58,040 [localhost-startStop-1] ERROR pool.ConnectionPool  - Unable to create initial connections of pool.
Message: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    Line | Method
->>  411 | handleNewInstance             in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1129 | createCommunicationsException in com.mysql.jdbc.SQLError
|    358 | <init> . . . . . . . . . . .  in com.mysql.jdbc.MysqlIO
|   2498 | coreConnect                   in com.mysql.jdbc.ConnectionImpl
|   2535 | connectOneTryOnly . . . . . . in     ''
|   2320 | createNewIO                   in     ''
|    834 | <init> . . . . . . . . . . .  in     ''
|     46 | <init>                        in com.mysql.jdbc.JDBC4Connection
|    411 | handleNewInstance . . . . . . in com.mysql.jdbc.Util
|    416 | getInstance                   in com.mysql.jdbc.ConnectionImpl
|    347 | connect . . . . . . . . . . . in com.mysql.jdbc.NonRegisteringDriver
|    266 | run                           in java.util.concurrent.FutureTask
|   1142 | runWorker . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
|    617 | run                           in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run . . . . . . . . . . . . . in java.lang.Thread
Caused by ConnectException: Connection refused: connect
->>   79 | socketConnect                 in java.net.DualStackPlainSocketImpl
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|    345 | doConnect                     in java.net.AbstractPlainSocketImpl
|    206 | connectToAddress . . . . . .  in     ''
|    188 | connect                       in     ''
|    172 | connect . . . . . . . . . . . in java.net.PlainSocketImpl
|    392 | connect                       in java.net.SocksSocketImpl
|    589 | connect . . . . . . . . . . . in java.net.Socket
|    538 | connect                       in     ''
|    434 | <init> . . . . . . . . . . .  in     ''
|    244 | <init>                        in     ''
|    256 | connect . . . . . . . . . . . in com.mysql.jdbc.StandardSocketFactory
|    308 | <init>                        in com.mysql.jdbc.MysqlIO
|   2498 | coreConnect . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
|   2535 | connectOneTryOnly             in     ''
|   2320 | createNewIO . . . . . . . . . in     ''
|    834 | <init>                        in     ''
|     46 | <init> . . . . . . . . . . .  in com.mysql.jdbc.JDBC4Connection
|    411 | handleNewInstance             in com.mysql.jdbc.Util
|    416 | getInstance . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
|    347 | connect                       in com.mysql.jdbc.NonRegisteringDriver
|    266 | run . . . . . . . . . . . . . in java.util.concurrent.FutureTask
|   1142 | runWorker                     in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run                           in java.lang.Thread
Error |
2016-08-23 16:19:00,132 [localhost-startStop-1] ERROR pool.ConnectionPool  - Unable to create initial connections of pool.
Message: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    Line | Method
->>  411 | handleNewInstance             in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1129 | createCommunicationsException in com.mysql.jdbc.SQLError
|    358 | <init> . . . . . . . . . . .  in com.mysql.jdbc.MysqlIO
|   2498 | coreConnect                   in com.mysql.jdbc.ConnectionImpl
|   2535 | connectOneTryOnly . . . . . . in     ''
|   2320 | createNewIO                   in     ''
|    834 | <init> . . . . . . . . . . .  in     ''
|     46 | <init>                        in com.mysql.jdbc.JDBC4Connection
|    411 | handleNewInstance . . . . . . in com.mysql.jdbc.Util
|    416 | getInstance                   in com.mysql.jdbc.ConnectionImpl
|    347 | connect . . . . . . . . . . . in com.mysql.jdbc.NonRegisteringDriver
|    266 | run                           in java.util.concurrent.FutureTask
|   1142 | runWorker . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
|    617 | run                           in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run . . . . . . . . . . . . . in java.lang.Thread
Caused by ConnectException: Connection refused: connect
->>   79 | socketConnect                 in java.net.DualStackPlainSocketImpl
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|    345 | doConnect                     in java.net.AbstractPlainSocketImpl
|    206 | connectToAddress . . . . . .  in     ''
|    188 | connect                       in     ''
|    172 | connect . . . . . . . . . . . in java.net.PlainSocketImpl
|    392 | connect                       in java.net.SocksSocketImpl
|    589 | connect . . . . . . . . . . . in java.net.Socket
|    538 | connect                       in     ''
|    434 | <init> . . . . . . . . . . .  in     ''
|    244 | <init>                        in     ''
|    256 | connect . . . . . . . . . . . in com.mysql.jdbc.StandardSocketFactory
|    308 | <init>                        in com.mysql.jdbc.MysqlIO
|   2498 | coreConnect . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
|   2535 | connectOneTryOnly             in     ''
|   2320 | createNewIO . . . . . . . . . in     ''
|    834 | <init>                        in     ''
|     46 | <init> . . . . . . . . . . .  in com.mysql.jdbc.JDBC4Connection
|    411 | handleNewInstance             in com.mysql.jdbc.Util
|    416 | getInstance . . . . . . . . . in com.mysql.jdbc.ConnectionImpl
|    347 | connect                       in com.mysql.jdbc.NonRegisteringDriver
|    266 | run . . . . . . . . . . . . . in java.util.concurrent.FutureTask
|   1142 | runWorker                     in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run                           in java.lang.Thread
Error |
2016-08-23 16:19:02,194 [localhost-startStop-1] ERROR pool.ConnectionPool  - Unable to create initial connections of pool.
Message: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    Line | Method
->>  411 | handleNewInstance             in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1129 | createCommunicationsException in com.mysql.jdbc.SQLError
|    358 | <init> . . . . . . . . . . .  in com.mysql.jdbc.MysqlIO
|   2498 | coreConnect                   in com.mysql.jdbc.ConnectionImpl
|   2535 | connectOneTryOnly . . . . . . in     ''
|   2320 | createNewIO                   in     ''
|    834 | <init> . . . . . . . . . . .  in     ''
|     46 | <init>                        in com.mysql.jdbc.JDBC4Connection
|    411 | handleNewInstance . . . . . . in com.mysql.jdbc.Util
|    416 | getInstance                   in com.mysql.jdbc.ConnectionImpl
|    347 | connect . . . . . . . . . . . in com.mysql.jdbc.NonRegisteringDriver
|    266 | run                           in java.util.concurrent.FutureTask
|   1142 | runWorker . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
|    617 | run                           in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run . . . . . . . . . . . . . in java.lang.Thread
Caused by ConnectException: Connection refused: connect
->>   79 | socketConnect                 in java.net.DualStackPlainSocketImpl
Error |
2016-08-23 16:19:02,205 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener  - Error initializing the application: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Message: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    Line | Method
->>  266 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
->>  266 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
->>  266 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
->>  266 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
->>  266 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Caused by MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
->>  266 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Caused by CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
->>  411 | handleNewInstance in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1129 | createCommunicationsException in com.mysql.jdbc.SQLError
|    358 | <init> .  in com.mysql.jdbc.MysqlIO
|   2498 | coreConnect in com.mysql.jdbc.ConnectionImpl
|   2535 | connectOneTryOnly in     ''
|   2320 | createNewIO in     ''
|    834 | <init> .  in     ''
|     46 | <init>    in com.mysql.jdbc.JDBC4Connection
|    411 | handleNewInstance in com.mysql.jdbc.Util
|    416 | getInstance in com.mysql.jdbc.ConnectionImpl
|    347 | connect . in com.mysql.jdbc.NonRegisteringDriver
|    266 | run       in java.util.concurrent.FutureTask
|   1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    617 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run . . . in java.lang.Thread
Caused by ConnectException: Connection refused: connect
->>   79 | socketConnect in java.net.DualStackPlainSocketImpl
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|    345 | doConnect in java.net.AbstractPlainSocketImpl
|    206 | connectToAddress in     ''
|    188 | connect   in     ''
|    172 | connect . in java.net.PlainSocketImpl
|    392 | connect   in java.net.SocksSocketImpl
|    589 | connect . in java.net.Socket
|    538 | connect   in     ''
|    434 | <init> .  in     ''
|    244 | <init>    in     ''
|    256 | connect . in com.mysql.jdbc.StandardSocketFactory
|    308 | <init>    in com.mysql.jdbc.MysqlIO
|   2498 | coreConnect in com.mysql.jdbc.ConnectionImpl
|   2535 | connectOneTryOnly in     ''
|   2320 | createNewIO in     ''
|    834 | <init>    in     ''
|     46 | <init> .  in com.mysql.jdbc.JDBC4Connection
|    411 | handleNewInstance in com.mysql.jdbc.Util
|    416 | getInstance in com.mysql.jdbc.ConnectionImpl
|    347 | connect   in com.mysql.jdbc.NonRegisteringDriver
|    266 | run . . . in java.util.concurrent.FutureTask
|   1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    617 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Error |
Forked Grails VM exited with errorJava HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

Кажется, Grails не может найти драйвер или что-то в этом роде. Однако мы видели, что файл JAR был зарегистрирован в каталоге .m2. Меня интересует одно: должен ли этот файл JAR появляться в списке зависимостей Grails:

введите здесь описание изображения

На картинке нет всего списка, но файла нет в списке. Это нормально? Должен ли файл появляться только в каталоге .m2 (в Ivy-кеше это то же самое, файл отсутствует)? Как вы думаете, доступна ли зависимость, когда я запускаю приложение? Распознает ли Grails драйвер, бросающий путь к классам?

Я действительно потерян.

Заранее большое спасибо за вашу помощь.


person user1364743    schedule 23.08.2016    source источник
comment
Обратите внимание, что классы MySQL JDBC Driver отображаются в трассировке ошибок. Это указывает на то, что JAR-файл MySQL JDBC используется вашим приложением. Неспособность найти драйвер JDBC будет совершенно другим исключением. Проблема в том, что ваше приложение не может подключиться к вашему экземпляру MySQL. Правильно ли вы настроили источник данных (URL, учетные данные)? В вашем примере кода отображается пустой пароль для пользователя root MySQL...   -  person jstell    schedule 23.08.2016


Ответы (1)


Но я бы сказал, следуйте шагам ниже один за другим:

  1. Проверьте, установлен ли сервер mysql на вашем компьютере. Дело может быть в том, что у вас установлен только Mysql-клиент.

  2. В вашем DataSource.groovy я вижу, что многие вещи либо отсутствуют, либо неправильно настроены. Я заметил несколько моментов: а) отсутствующая конфигурация диалекта б) отсутствующий номер порта. для подключения к серверу

Ниже исправлен DataSource.groovy

dataSource {
    pooled = true
    jmxExport = true
    //driverClassName = "org.h2.Driver"
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    username = "sa"
    password = ""
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
//    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
    cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
    singleSession = true // configure OSIV singleSession mode
    flush.mode = 'manual' // OSIV session flush mode outside of transactional context
}

// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
            //url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
            url = "jdbc:mysql://localhost:3306/test"//you had a missing port here
            driverClassName = "com.mysql.jdbc.Driver"
            username = "root"
            password = ""
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            //url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
            url = "jdbc:mysql://localhost/test"
            driverClassName = "com.mysql.jdbc.Driver"
            username = "root"
            password = ""
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            //url = "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
            url = "jdbc:mysql://localhost/test"
            driverClassName = "com.mysql.jdbc.Driver"
            username = "root"
            password = ""
            properties {
               // See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
               jmxEnabled = true
               initialSize = 5
               maxActive = 50
               minIdle = 5
               maxIdle = 25
               maxWait = 10000
               maxAge = 10 * 60000
               timeBetweenEvictionRunsMillis = 5000
               minEvictableIdleTimeMillis = 60000
               validationQuery = "SELECT 1"
               validationQueryTimeout = 3
               validationInterval = 15000
               testOnBorrow = true
               testWhileIdle = true
               testOnReturn = false
               jdbcInterceptors = "ConnectionState"
               defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
            }
        }
    }
}

Надеюсь поможет!! Дайте мне знать, если у вас возникнут какие-либо проблемы после нового DataSource.groovy.

person Vinay Prajapati    schedule 23.08.2016
comment
Спасибо! Это было очевидно. Я забыл установить сервер MySQL :). Я же говорил, я новичок! Теперь, что касается файла DataSource.groovy, нет необходимости предоставлять «диалект» гибернации SQL. Я думаю, что это оператор по умолчанию в Grails (но я думаю, что все равно лучше его уточнить). И нет необходимости также указывать порт (я нахожусь на локальном хосте, и строка «grails.server.port.http» не является точной в файле BuildConfig.groovy, поэтому по умолчанию для меня это «8080»). Итак, еще раз спасибо за вашу помощь! Пока. - person user1364743; 24.08.2016