在 Grails 3.x 中安装和使用 MongoDB

Installing and using MongoDB in Grails 3.x

我一直在关注 Manning 的 Grails In Action,但他们关于配置数据源的部分对于 Grails 3.0.3 来说已经过时了。

我的意图是将H2 的默认数据源转换为MongoDB 版本3.0.2。 Google 搜索产生了相互矛盾的结果——许多答案通常针对早期版本的 Grails,它使用 'BuildConfig.groovy' 和 'DataSources.groovy' 来建立插件和数据源。

我已经下载 the 3.0.2 JDBC for MongoDB 并将其存储在不同的文件夹(即应用程序的根目录、创建的 /lib/ 文件夹和 /grails-app/conf/ 中)但没有成功。

我的 application.yml 文件显示:



    ---
    grails:
        profile: web
        codegen:
            defaultPackage: qotd
    info:
        app:
            name: '@info.app.name@'
            version: '@info.app.version@'
            grailsVersion: '@info.app.grailsVersion@'
    spring:
        groovy:
            template:
                check-template-location: false

    ---
    grails:
        mime:
            disable:
                accept:
                    header:
                        userAgents:
                            - Gecko
                            - WebKit
                            - Presto
                            - Trident
            types:
                all: '*/*'
                atom: application/atom+xml
                css: text/css
                csv: text/csv
                form: application/x-www-form-urlencoded
                html: 
                  - text/html
                  - application/xhtml+xml
                js: text/javascript
                json:
                  - application/json
                  - text/json
                multipartForm: multipart/form-data
                rss: application/rss+xml
                text: text/plain
                hal: 
                  - application/hal+json
                  - application/hal+xml
                xml:
                  - text/xml
                  - application/xml
        urlmapping:
            cache:
                maxsize: 1000
        controllers:
            defaultScope: singleton
        converters:
            encoding: UTF-8
        views:
            default:
                codec: html
            gsp:
                encoding: UTF-8
                htmlcodec: xml
                codecs:
                    expression: html
                    scriptlets: html
                    taglib: none
                    staticparts: none
    ---
    hibernate:
        cache:
            queries: false
            use_second_level_cache: true
            use_query_cache: false
            region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'

    dataSource:
        pooled: true
        jmxExport: true
        host: 'localhost'
        port: 27017
        driverClassName: mongodb-driver-3.0.2.jar
        databaseName: 'test_db'

    environments:
        development:
            dataSource:
                dbCreate: create
                url: jdbc:mongodb://localhost:27017
        test:
            dataSource:
                dbCreate: update
                url: jdbc:mongodb://localhost:27017
        production:
            dataSource:
                dbCreate: update
                url: jdbc:mongodb://localhost:27017
                properties:
                    jmxEnabled: true
                    initialSize: 5
                    maxActive: 50
                    minIdle: 5
                    maxIdle: 25
                    maxWait: 10000
                    maxAge: 600000
                    timeBetweenEvictionRunsMillis: 5000
                    minEvictableIdleTimeMillis: 60000
                    validationQuery: SELECT 1
                    validationQueryTimeout: 3
                    validationInterval: 15000
                    testOnBorrow: true
                    testWhileIdle: true
                    testOnReturn: false
                    jdbcInterceptors: ConnectionState
                    defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED

我的 build.gradle 文件显示:



    buildscript {
        ext {
            grailsVersion = project.grailsVersion
        }
        repositories {
            mavenLocal()
            maven { url "https://repo.grails.org/grails/core" }
        }
        dependencies {
            classpath "org.grails:grails-gradle-plugin:$grailsVersion"
            classpath 'com.bertramlabs.plugins:asset-pipeline-gradle:2.1.1'
        }
    }

    plugins {
        id "io.spring.dependency-management" version "0.5.2.RELEASE"
    }

    version "0.1"
    group "qotd"

    apply plugin: "spring-boot"
    apply plugin: "war"
    apply plugin: "asset-pipeline"
    apply plugin: 'eclipse'
    apply plugin: 'idea'
    apply plugin: "org.grails.grails-web"
    apply plugin: "org.grails.grails-gsp"

    ext {
        grailsVersion = project.grailsVersion
        gradleWrapperVersion = project.gradleWrapperVersion
    }

    assets {
        minifyJs = true
        minifyCss = true
    }

    repositories {
        mavenLocal()
        maven { url "https://repo.grails.org/grails/core" }
    }

    dependencyManagement {
        imports {
            mavenBom "org.grails:grails-bom:$grailsVersion"
        }
        applyMavenExclusions false
    }

    dependencies {
        compile "org.springframework.boot:spring-boot-starter-logging"
        compile "org.springframework.boot:spring-boot-starter-actuator"
        compile "org.springframework.boot:spring-boot-autoconfigure"
        compile "org.springframework.boot:spring-boot-starter-tomcat"
        compile "org.grails:grails-dependencies"
        compile "org.grails:grails-web-boot"
        compile 'org.mongodb:mongodb-driver:3.0.2'

        compile "org.grails.plugins:hibernate"
        compile "org.grails.plugins:cache"
        compile "org.hibernate:hibernate-ehcache"

        runtime "org.grails.plugins:asset-pipeline"
        runtime "org.grails.plugins:scaffolding"

        testCompile "org.grails:grails-plugin-testing"
        testCompile "org.grails.plugins:geb"

        // Note: It is recommended to update to a more robust driver (Chrome, Firefox etc.)
        testRuntime 'org.seleniumhq.selenium:selenium-htmlunit-driver:2.44.0'

        console "org.grails:grails-console"
    }

    task wrapper(type: Wrapper) {
        gradleVersion = gradleWrapperVersion
    }

... 最后,当我尝试执行 $ grails run-app 时的实际堆栈跟踪是:



    java.util.concurrent.ExecutionException: org.gradle.tooling.BuildException: Could not execute build using Gradle distribution 'https://services.gradle.org/distributions/gradle-2.3-bin.zip'.
        at java_util_concurrent_Future$get.call(Unknown Source)
        at run-app.run(run-app.groovy:90)
        at org.grails.cli.profile.commands.script.GroovyScriptCommand.handle(GroovyScriptCommand.groovy:152)
        at org.grails.cli.profile.DefaultProfile.handleCommand(DefaultProfile.groovy:177)
        at org.grails.cli.GrailsCli.handleCommand(GrailsCli.groovy:239)
        at org.grails.cli.GrailsCli.handleCommand(GrailsCli.groovy:220)
        at org.grails.cli.GrailsCli.execute(GrailsCli.groovy:198)
        at org.grails.cli.GrailsCli.main(GrailsCli.groovy:99)
    Caused by: org.gradle.tooling.BuildException: Could not execute build using Gradle distribution 'https://services.gradle.org/distributions/gradle-2.3-bin.zip'.
        at org.gradle.tooling.internal.consumer.ResultHandlerAdapter.onFailure(ResultHandlerAdapter.java:57)
        at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor.run(DefaultAsyncConsumerActionExecutor.java:57)
        at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl.run(DefaultExecutorFactory.java:64)
        at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
        at org.gradle.tooling.internal.consumer.DefaultBuildLauncher.run(DefaultBuildLauncher.java:71)
        at org.grails.cli.gradle.GradleUtil$_runBuildWithConsoleOutput_closure4.doCall(GradleUtil.groovy:109)
        at org.grails.cli.gradle.GradleUtil$_withProjectConnection_closure2.doCall(GradleUtil.groovy:89)
        at org.grails.cli.gradle.GradleUtil$_withProjectConnection_closure2.call(GradleUtil.groovy)
        at grails.io.support.SystemOutErrCapturer.withNullOutput(SystemOutErrCapturer.groovy:64)
        at org.grails.cli.gradle.GradleUtil.withProjectConnection(GradleUtil.groovy:88)
        at org.grails.cli.gradle.GradleUtil.runBuildWithConsoleOutput(GradleUtil.groovy:104)
        at org.grails.cli.gradle.GradleInvoker.invokeMethod(GradleInvoker.groovy:50)
        at org.grails.cli.gradle.GradleAsyncInvoker$_invokeMethod_closure2.doCall(GradleAsyncInvoker.groovy:51)
        at org.grails.cli.gradle.GradleAsyncInvoker$_invokeMethod_closure2.doCall(GradleAsyncInvoker.groovy)
    Caused by: org.gradle.internal.exceptions.LocationAwareException: Execution failed for task ':bootRun'.
        at org.gradle.initialization.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:77)
        at org.gradle.initialization.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:47)
        at org.gradle.initialization.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:30)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:108)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)
        at org.gradle.tooling.internal.provider.BuildModelAction.run(BuildModelAction.java:43)
        at org.gradle.tooling.internal.provider.BuildModelAction.run(BuildModelAction.java:30)
        at org.gradle.tooling.internal.provider.ConfiguringBuildAction.run(ConfiguringBuildAction.java:119)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:48)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator.run(DaemonStateCoordinator.java:246)
        at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl.run(DefaultExecutorFactory.java:64)
    Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':bootRun'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:306)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
        at org.gradle.execution.DefaultBuildExecuter.access0(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter.proceed(DefaultBuildExecuter.java:68)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
        ... 34 more
    Caused by: org.gradle.process.internal.ExecException: Process 'command '/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.85.x86_64/jre/bin/java'' finished with non-zero exit value 1
        at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:365)
        at org.gradle.process.internal.DefaultJavaExecAction.execute(DefaultJavaExecAction.java:31)
        at org.gradle.api.tasks.JavaExec.exec(JavaExec.java:60)
        at org.springframework.boot.gradle.run.BootRunTask.exec(BootRunTask.java:58)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:218)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:211)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:200)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:585)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:568)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
        ... 57 more
    | Error Failed to start server

如有任何帮助,我们将不胜感激;我花了很多时间用头撞桌子,却发现无用的搜索结果。

是的,找到有关配置 Grails 3.0 以使用 MongoDB 的最新文档是一项挑战。下面的解决方案是从各种来源拼凑而成的。

build.gradle

dependencies {
   ...
   compile "org.grails.plugins:mongodb"
   ...
   }

您不需要手动下载和安装任何 JDBC 个文件。


grails-app/conf/application.yml

environments:
   development:
      grails:
         mongodb:
            connectionString: "mongodb://localhost:27017/project-db"


grails-app/domain/com/example/Book.groovy

package com.example

import org.bson.types.ObjectId

class Book {
   ObjectId id
   String   title
   static mapWith = "mongo"
   }


我从 Grails 3.0.1 开始就成功地使用了这种方法,它仍然适用于 3.0.4。

Dem Pilafian 是伟大而正确的。我的只是略有不同。您可以在 类 中省略映射并依靠 mongodb 直接存储您的对象。您需要做的就是从您的项目中删除休眠。

使用 Grails 3.1.7

build.gradle

dependencies {
  compile "org.grails.plugins:mongodb"
  //compile "org.grails.plugins:hibernate4"
  //compile "org.hibernate:hibernate-ehcache"
  //runtime "com.h2database:h2"
}

我已经注释掉了 hibernate 和 h2 依赖项。当然,如果你只使用 mongodb.

,你可以完全删除它们

grails-app/conf/application.yml

environments:
  development:
    grails:
      mongodb:
        host: "hostname"
        port: 27017
        databaseName: development

在 application.yml 中,您需要删除 hibernate: 部分和 driverClassName: org.h2.Driver。 有关更多背景信息以及其他配置选项,请参阅:GORM Grails MongoDB

这样,您将完全绕过休眠,并且不需要在 类 中定义映射。您的对象将作为结构化文档直接存储在 mongo.