How to make MySQL work on grails 2.0

17,872

Solution 1

install-dependency just downloads the jar and puts it in your Ivy cache. But you haven't declared that your application has a dependency on that jar. BuildConfig.groovy has a commented-out dependency declaration for the MySQL driver. Just uncomment that and update the version if you want and it will add it to your application's classpath. It would also download the jar to your Ivy cache if you hadn't done that with install-dependency.

Solution 2

I just did a grails>clean and it worked

Solution 3

I ended up writing a groovy script that tests connection to MySQL. The code follows. Place it in scripts/TestMysql.groovy and run e.g. as

grails test test-mysql localhost 3306 test-db grails-user grails-password

The first "test" is to run the script in the test environment, in case there are any changes in DataSource.groovy.

If you can connect to MySQL with this script, at the very least you will know the correct settings for your DataSource.groovy. In case of success it also prints the relevant dataSource {} section to be inserted into DataSource.groovy.

/* Testing grails/GORM connection to mysql
 * Call this script "scripts/TestMysql.groovy"
 * Usage: "grails test-mysql" or, to run in another environment, e.g. "grails test test-mysql"
 * (This is in case you have changed DataSource.groovy and nothing is working.)
 *
 * Up to five parameters:
 * grails test test-mysql <host> <port> <database> <user> <password>
 * e.g. grails test test-mysql localhost 3306 test root rootpassword.
 * The database name can also be empty.
 */

import groovy.sql.Sql

includeTargets << grailsScript("_GrailsInit") << grailsScript("_GrailsArgParsing")

target(main: "The description of the script goes here!") {

    def list=argsMap['params']
    def host=list[0] ? list[0] : 'localhost'  
    def port=list[1] ? list[1] : '3306'       
    def db=list[2] ? list[2] : ''             // can leave empty
    def user=list[3] ? list[3] : 'grails'      
    def pswd=list[4] ? list[4] : 'grails'

    println "Connecting to " + host + ":" + port
    println "Database:" + db
    println "User: " + user
    println "Password: " + pswd

    def jdbc_string='jdbc:mysql://' + host + ':' + port + '/' + db

    def sql
    try {
        sql = Sql.newInstance(jdbc_string, user, pswd, "com.mysql.jdbc.Driver")
    } catch (com.mysql.jdbc.exceptions.jdbc4.CommunicationsException e) {
        println "ERROR! Cannot connect to " + host + ":" + port
        println "Check host, port, your open ports and other firewall settings; try to connect with some other program"
        println ""
        println e
        return
    } catch (com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException e) {
        println "MySQL ERROR, perhaps wrong database name!"
        println ""
        println e
        return
    } catch (java.sql.SQLException e) {
        println "MySQL ERROR, perhaps wrong login/password!"
        println ""
        println e
        return
    }

    println "SUCCESS! Connected to MySQL"
    def query = "SHOW DATABASES"

    println "Executing query " + query + "..."
    sql.eachRow(query) {
      println it
    }

    println "OK, Done!"

    println """
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:mysql://${host}:${port}/${db}"
            username="${user}"
            password="${pswd}"
        }
        """

}

setDefaultTarget(main)

Update: indeed, once this script was working, it was easy to make Grails work as well. I just had to do grails clean, delete all *.class files that survived, restore the original DataSource.groovy, and then grails compile --refresh-dependencies. Then change DataSource.groovy, and it works like a charm.

Here is my working DataSource.groovy:

dataSource {
    pooled = true
    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'
}
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:mysql://localhost:8890/test"
            username="grails"
            password="grails"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
            pooled = true
            properties {
               maxActive = -1
               minEvictableIdleTimeMillis=1800000
               timeBetweenEvictionRunsMillis=1800000
               numTestsPerEvictionRun=3
               testOnBorrow=true
               testWhileIdle=true
               testOnReturn=true
               validationQuery="SELECT 1"
            }
        }
    }
}
Share:
17,872

Related videos on Youtube

Mikey
Author by

Mikey

I am learning Grails. It is awesome.

Updated on June 04, 2022

Comments

  • Mikey
    Mikey almost 2 years

    Grails 2.0 seems to have some changes to DataSource.groovy and I don't seem to be able to get mysql running as it was in 1.3.7

    I did grails install-dependency mysql:mysql-connector-java:5.1.16 rather than just dumping the .jar in lib. I hear this is the way to do it these days.

    Here is what I have replaced in my DataSource.groovy:

    driverClassName = "org.h2.Driver"
    ...
    url = "jdbc:h2:mem:devDb;MVCC=TRUE"
    

    With

    driverClassName = "com.mysql.jdbc.Driver"
    ...
    url = "jdbc:mysql://localhost:3306/${dbNamer}?autoreconnect=true"
    

    Changing of course the username, password and dbNamer to valid entries... What am I doing wrong? Is there a grails 2.0 tutorial that covers setting up mysql?

    I get this monster error:

    | Loading Grails 2.0.0
    | Configuring classpath.
    | Environment set to development.....
    | Packaging Grails application.....
    | Compiling 1 source files.....
    | Running Grails application
    | Error 2012-01-16 21:39:10,134 [Thread-9] ERROR context.GrailsContextLoader  - Error     executing bootstraps: 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 org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    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 org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
        Line | Method
    ->>  334 | innerRun  in java.util.concurrent.FutureTask$Sync
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    |    166 | run       in java.util.concurrent.FutureTask
    |   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    603 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    679 | 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 org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    ->>  334 | innerRun  in java.util.concurrent.FutureTask$Sync
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    |    166 | run       in java.util.concurrent.FutureTask
    |   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    603 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    679 | 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 org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    ->>  334 | innerRun  in java.util.concurrent.FutureTask$Sync
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    |    166 | run       in java.util.concurrent.FutureTask
    |   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    603 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    679 | 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 org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    ->>  334 | innerRun  in java.util.concurrent.FutureTask$Sync
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    |    166 | run       in java.util.concurrent.FutureTask
    |   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    603 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    679 | 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 org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    ->>  334 | innerRun  in java.util.concurrent.FutureTask$Sync
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    |    166 | run       in java.util.concurrent.FutureTask
    |   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    603 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    679 | run . . . in java.lang.Thread
    Caused by MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    ->>  334 | innerRun  in java.util.concurrent.FutureTask$Sync
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    |    166 | run       in java.util.concurrent.FutureTask
    |   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    603 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    679 | run . . . in java.lang.Thread
    Caused by SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    ->> 1429 | createConnectionFactory in org.apache.commons.dbcp.BasicDataSource
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    |   1371 | createDataSource in     ''
    |   1044 | getConnection in     ''
    |    334 | innerRun  in java.util.concurrent.FutureTask$Sync
    |    166 | run . . . in java.util.concurrent.FutureTask
    |   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    679 | run       in java.lang.Thread
    Caused by ClassNotFoundException: com.mysql.jdbc.Driver
    ->>  217 | run       in java.net.URLClassLoader$1
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    |    205 | findClass in java.net.URLClassLoader
    |    321 | loadClass in java.lang.ClassLoader
    |    266 | loadClass in     ''
    |   1420 | createConnectionFactory in org.apache.commons.dbcp.BasicDataSource
    |   1371 | createDataSource in     ''
    |   1044 | getConnection in     ''
    |    334 | innerRun  in java.util.concurrent.FutureTask$Sync
    |    166 | run . . . in java.util.concurrent.FutureTask
    |   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    679 | run       in java.lang.Thread
    
  • Mikey
    Mikey over 12 years
    Did I just forget about having to do this before, or is the dependency thing new in 2.0? or is it because I did install-dependency instead of dropping the jar?
  • Burt Beckwith
    Burt Beckwith over 12 years
    It's been around since 1.2. Like I said, install-dependency is a global thing - it just downloads the jar and caches it, but has no effect on the current app. See grails.org/doc/latest/ref/Command%20Line/…
  • aman.nepid
    aman.nepid almost 12 years
    it also worked for me. the command is like app_name>grails clean
  • moeTi
    moeTi over 11 years
    yep totally worked for me, no changes in BuildConfig.groovy required
  • rhgb
    rhgb over 10 years
    I had the same problem while dropping jar into libs directly instead of install-dependency. This worked for me
  • Sergey Orshanskiy
    Sergey Orshanskiy over 10 years
    It seems, though, that "grails clean" has no effect on the *.class files that were compiled from DataSource.groovy and BuildConfig.groovy. (I don't know when those files were created.) But deleting and/or recompiling them manually with groovyc works!