本练习是采用InterlliJ IDEA开发。首先新建一个Uses项目。
grails采用GORM连接mongodb数据库,但开发工具中已经集成好,无需配置。
英文开发文档在:http://jkuehn.github.io/gorm-mongodb/
可以自己查看,本文只介绍一个连接的小例子,并实现存储一个实体类。
首先需要建立连接字符串,只需在Configuration的文件下的DataSource.groovy的最下面写上:
grails {
mongo {
// host = "10.52.12.53"
host = "localhost"
port = 27017
//username = "tapuser"
//password = "tiger123"
// replicaSet = [ "localhost:27071", "localhost:37071"]
databaseName = "cjbdb"
}
}
首先建立一个Domain Class User,代码如下所示
package users
class User {
String username;
String password;
static transactional = 'mongo'
static constraints = {
}
}
static transactional = ‘mongo'必须要有否则不能存储到数据库中去。
package users
class UserController {
def index() {
//new User(username: "lll", password: "lll").save(flush:true)
// new User(username: "hello1",password: "hello1").save(flush: true);
for(int i = 0;i<10;i++){
new User(username: "user"+i,password: "hello" +i).save(flush: true);
}
def user = User.findByUsername("lll");
}
}
controller类如上所示;
然后运行项目,打开数据库查看则可以看到插入的数据库
本人用的数据库的图形界面是MongoVUE.
其他查询语句和不同环境下的连接方式,可以在英文开发文档里面查看。