Installing and using MongoDB in Grails 3.x

自作多情 提交于 2019-12-01 08:00:59

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.

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.

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