简体   繁体   English

如何在Groovy / Grails中使用Mongodb的Java驱动程序

[英]How to use Mongodb's java driver in groovy/grails

I'm having a hard time trying to "import" Mongodb's java driver into Groovy/Grails. 我很难尝试将Mongodb的Java驱动程序“导入”到Groovy / Grails中。 In other words, what dependency gets added to the config files and where? 换句话说,什么依赖项被添加到配置文件中以及在哪里? At this point, I have the file "mongo-java-driver-2.12.1.jar" downloaded. 此时,我已下载文件“ mongo-java-driver-2.12.1.jar”。

Did you look into using the grails mongo driver here? 您是否考虑过在这里使用grails mongo驱动程序? https://grails.org/plugins/mongodb . https://grails.org/plugins/mongodb This plugin automatically adds the Mongodb java driver and the equivalent helper beans to grab db connections right in your servers. 该插件会自动添加Mongodb Java驱动程序和等效的帮助器bean,以直接在您的服务器中获取数据库连接。 It also primarily adds GORM support. 它还主要增加了对GORM的支持。 Add the following to your BuildConfig.groovy plugins block: 将以下内容添加到您的BuildConfig.groovy插件块中:

plugins {
  compile ":mongodb:3.0.1"
}

Also, depends on the version of grails you are using. 另外,取决于您使用的grails的版本。 This is recommended for grails 2.3.7 or above. 建议在grails 2.3.7或更高版本上使用。 However, if you are using anything2.3.7 or below you need to add this to your BuildConfig.groovy 但是,如果您使用的是2.3.7或更低版​​本,则需要将其添加到BuildConfig.groovy

dependencies {
  compile 'org.grails:grails-datastore-gorm:3.0.4.RELEASE'
  compile 'org.grails:grails-datastore-core:3.0.4.RELEASE'
  test 'org.grails:grails-datastore-simple:3.0.4.RELEASE'
}

I have solved this issue. 我已经解决了这个问题。 You don't actually import the jar or anything like that. 您实际上并没有导入jar或类似的东西。 What you do is that when you declare the Mongo GORM plugin dependency by putting this line 您要做的是,当您通过以下内容声明Mongo GORM插件依赖项时

compile ':mongodb:3.0.1'

in your BuildConfig.groovy file, you actually, are importing the driver, after that its as simple as: 实际上,在BuildConfig.groovy文件中,您正在导入驱动程序,此后就很简单了:

import com.mongodb.*
MongoClient mongoClient = new MongoClient("localhost", 27017)
            DB db = mongoClient.getDB("db");

and now you can use the db variable to access the database. 现在,您可以使用db变量访问数据库。

Adding 新增中

compile 'org.mongodb:mongo-java-driver:2.13.1'

in Dependency section of BuildConfig.groovy worked for me. 在BuildConfig.groovy的Dependency部分中为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM