从Grails连接到Postgres的问题

时间:2014-09-28 00:31:26

标签: postgresql grails

我已经验证我可以使用Java测试程序连接到postgres数据库。我还验证了我可以使用一个小的Grails testDB项目进行连接。但是当我尝试运行我的大型项目时,同样的BuildConfig.groovy,它就失败了。

我已经在postgres jar中尝试了不同的jdbc版本(例如,4而不是41),但它没有帮助。

我一直在搜索stackoverflow和其他任何我无法找到的东西(例如,"帮助我stackoverflow,你的唯一希望")。

我的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'
        compile 'org.postgresql:postgresql:9.3-1101-jdbc41'
        runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
        test "org.grails:grails-datastore-test-support:1.0-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.7'
        compile ":asset-pipeline:1.9.6"
        compile ":twitter-bootstrap:3.2.1"
        // compile ":jquery-dialog:2.0.3"

        // plugins needed at runtime but not for compilation
        runtime ":hibernate4:4.3.5.5" // or ":hibernate:3.6.10.15"
        runtime ":database-migration:1.4.0"
        runtime ":jquery:1.11.1"
        runtime ":twitter-bootstrap:3.2.1"

    }
}

我的DataSource.groovy文件包含

dataSource {
    pooled = true
    jmxExport = true
    url = "jdbc:postgresql://150.18.178.9:5432/myDB"
    driverClassName = "org.postgresql.Driver"
    dbCreate = "update"
    username = "user"
    password = "password"
    dialect = net.sf.hibernate.dialect.PostgreSQLDialect
}
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
}

// environment specific settings
environments {
    development {
        dataSource { // database dev
            dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
            url="jdbc:postgresql://150.18.178.9:5432/dev"
            username = "user"
            password = "password"
        }
    }
    test {
        dataSource { 
            dbCreate = "update"
            url="jdbc:postgresql://150.18.178.9:5432/test"
            username = "user"
            password = "password"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url="jdbc:postgresql://150.18.178.9:5432/myDB"
            username = "user"
            password = "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
            }
        }
    }
}

当我尝试运行我的应用程序时,我得到:

/usr/java/latest/bin/java -Dgrails.home=/home/iank/software/grails/latest -Dbase.dir=/home/iank/IdeaProjects/nderground -Dtools.jar=/usr/java/latest/lib/tools.jar -Dgroovy.starter.conf=/home/iank/software/grails/latest/conf/groovy-starter.conf -Xmx768M -Xms768M -XX:MaxPermSize=256m -XX:PermSize=256m -javaagent:/home/iank/software/grails/latest/lib/org.springframework/springloaded/jars/springloaded-1.2.0.RELEASE.jar -noverify -Dspringloaded=profile=grails -Didea.launcher.port=7535 -Didea.launcher.bin.path=/home/iank/software/idea-IU-135.909/bin -Dfile.encoding=UTF-8 -classpath /home/iank/software/grails/latest/lib/org.codehaus.groovy/groovy-all/jars/groovy-all-2.3.6.jar:/home/iank/software/grails/latest/dist/grails-bootstrap-2.4.3.jar:/home/iank/software/idea-IU-135.909/lib/idea_rt.jar com.intellij.rt.execution.application.AppMain org.codehaus.groovy.grails.cli.support.GrailsStarter --main org.codehaus.groovy.grails.cli.GrailsScriptRunner --conf /home/iank/software/grails/latest/conf/groovy-starter.conf "run-app -plain-output"
|Loading Grails 2.4.3
|Configuring classpath
.
|Environment set to development
.................................
|Packaging Grails application
...........
|Compiling 1 source files
............................
|Running Grails application
| Error 2014-09-27 17:16:38,021 [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': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
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': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
    Line | Method
->>  262 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    615 | 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': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
->>  262 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
->>  262 | run       in java.util.concurrent.FutureTask
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run       in java.lang.Thread
Caused by IllegalArgumentException: object is not an instance of declaring class
->>   22 | doCall    in nderground.User$__clinit__closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|    262 | run       in java.util.concurrent.FutureTask
|   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    615 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run . . . in java.lang.Thread
Error |
Forked Grails VM exited with error
|Server running. Browse to http://localhost:8080/nderground

Process finished with exit code 1

任何帮助都将深表感谢。我的进展完全停滞不前,除了尝试一块一块地重建项目之外,我不知道该做什么。

非常感谢......

3 个答案:

答案 0 :(得分:1)

通过创建一个有效且慢慢添加代码的Grails项目,我能够找到问题所在。我有一个未正确指定的约束。

class User {
	String handle
    String emailAddr
	String salt
	String password
    boolean isAdmin
    
    String toString()
    {
        String rslt = "$handle"
        return rslt 
    }

    static constraints = {
        handle blank : false, nullable : false, unique : true
        emailAddr blank : false, nullable : false, unique : true, email : true
		salt blank: false, nullable: false
		password blank: false, nullable: false
		isAdmin false  <<======= This is the problem!
    }
    
    static mapping = {
        table 'users'
        handle index : 'handle_Ix'
        emailAddr index: 'email_ix'
		isAdmin defaultValue: false
    }
}

这应该在静态映射部分:

static mapping = {
        table 'users'
        handle index : 'handle_Ix'
        emailAddr index: 'email_ix'
		isAdmin defaultValue: false  <<== This is the right way to set the default
    }

说得客气一点,令人讨厌的是,错误显示为线程创建错误,没有任何其他错误指示​​。

答案 1 :(得分:0)

正如@EElke在评论中指出的那样,没有迹象表明Postgres是问题所在;你应该看到的错误是Error creating bean with name 'sessionFactory' ... object is not an instance of declaring class

我的猜测是net.sf.hibernate.dialect.PostgreSQLDialect是问题 - 用org.hibernate.dialect.PostgreSQLDialect替换它。

另外,删除这个:

runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'

因为你已经

compile 'org.postgresql:postgresql:9.3-1101-jdbc41'

和运行时范围包括编译范围的依赖关系。

答案 2 :(得分:0)

感谢你回答我的问题,伯特。我非常感谢你的时间。我对DataSource.groovy做了这个改动:

&#13;
&#13;
dataSource {
    pooled = true
    jmxExport = true
	url = "jdbc:postgresql://150.18.178.9:5432/myDB"
	driverClassName = "org.postgresql.Driver"
    dbCreate = "update"
    username = "user"  // the real user and password would normally be here
    password = "password"
    // dialect = net.sf.hibernate.dialect.PostgreSQLDialect
	dialect = org.hibernate.dialect.PostgreSQLDialect
}
&#13;
&#13;
&#13;

不幸的是,问题仍然存在。

只要您不必查看黑匣子,框架就会很棒。但是在这种情况下,错误发生在框架中的某个地方并且被遮盖了。

我通过JDBC有很多SQL经验,此时我认为我可以尝试从Grails应用程序中删除Hibernate。我只有五个左右的表,SQL查询非常简单。鉴于我花费了大量时间,我可以在相同的时间内重写Java JDBC中的所有内容。 Hibernate没有提供我的优势。

我喜欢自己处理数据库连接的一件事是我可以在连接数据库和SQL时记录更清晰的错误。

[后]

我考虑摆脱Hibernate。我当然可以在没有Hibernate的情况下构建Grails应用程序。但是,Hibernate基础架构不仅为您提供数据访问和更新。 Grails Hibernate基础结构还隐藏了有关连接池的所有细节(据我所知,在Tomcat上,它使用Tomcat的连接池)。为了使其在Grails Hibernate之外工作,您必须实现JNDI Connection数据源。这意味着更改Tomcat文件(web.xml和configure.xml)。因此,您不能再只创建Grails WAR文件并将其放在Tomcat Web服务器上。所以看起来我一直在寻找问题的根源。当我找到它时,我会再次发帖。