Installing and using MongoDB in Grails 3.x

↘锁芯ラ 提交于 2019-12-01 07:10:45

问题


I've been following Manning's Grails In Action, but their section on configuring data sources is woefully out-of-date for Grails 3.0.3.

My intention is to convert from the default data source of H2 to MongoDB version 3.0.2. Google searches have yielded conflicting results -- many answers are often for earlier versions of Grails, which used 'BuildConfig.groovy' and 'DataSources.groovy' in order to establish plug-ins and data sources.

I've downloaded the 3.0.2 JDBC for MongoDB and stored it in various folders (i.e. the root of the application, a created /lib/ folder, and in /grails-app/conf/) without success.

My application.yml file reads:



    ---
    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

My build.gradle file reads:



    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
    }

... and finally, the actual stack trace when I try to execute $ grails run-app is:



    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$1$1.run(DefaultAsyncConsumerActionExecutor.java:57)
        at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.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$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.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$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
        at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.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.access$200(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$2.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

Any help would be greatly appreciated; many hours have been spent slamming my head against my desk and finding unhelpful search results.


回答1:


Yeah, it's a challenge finding up-to-date documentation for configuring Grails 3.0 to use MongoDB. The solution below was cobbled together from various sources.

build.gradle

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

You do not need to manually download and install any JDBC files.


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"
   }


I've been successfully using this approach since Grails 3.0.1, and it's still working with 3.0.4.




回答2:


Dem Pilafian is great and correct. Mine is just slightly different. You can leave out the mapping in your classes and rely on mongodb to directly store your objects. All you need to do is remove hibernate from your project.

Using 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"
}

I've commented out the hibernate and h2 dependencies. You can delete them entirely of course, if you use only mongodb.

grails-app/conf/application.yml

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

In the application.yml you need to remove the hibernate: section and the driverClassName: org.h2.Driver. For more background information as well as additional configuration options, refer to: GORM Grails MongoDB

This way, you will bypass hibernate completely and don't need to define a mapping in your classes. Your objects will be directly stored as structured documents in mongo.



来源:https://stackoverflow.com/questions/31707811/installing-and-using-mongodb-in-grails-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!