1

我需要在我的应用程序中使用 findAndModify 和 grails 和 mongoDB。我使用了这段代码:

public static String getNextId(DB db, String seq_name) {
String sequence_collection = "seq"; // the name of the sequence collection
String sequence_field = "seq"; // the name of the field which holds the sequence

DBCollection seq = db.getCollection(sequence_collection); // get the collection (this will create it if needed)

// this object represents your "query", its analogous to a WHERE clause in SQL
DBObject query = new BasicDBObject();
query.put("_id", seq_name); // where _id = the input sequence name

// this object represents the "update" or the SET blah=blah in SQL
DBObject change = new BasicDBObject(sequence_field, 1);
DBObject update = new BasicDBObject("$inc", change); // the $inc here is a mongodb command for increment

// Atomically updates the sequence field and returns the value for you
DBObject res = seq.findAndModify(query, new BasicDBObject(), new BasicDBObject(), false, update, true, true);
return res.get(sequence_field).toString();
}

它工作成功。但是现在我想在没有本机 mongodb 对象的情况下使用 findAndModify,并使用 GORM。这项工作有什么解决方案吗?

4

2 回答 2

3

没有本机 API 就无法实现这一点,但是您可以像这样编写更紧凑的代码:

def collection = Seq.collection
collection.findAndModify([_id: seq_name ], [ "\$inc": [seq:1] ])
于 2013-05-18T10:14:18.087 回答
0

使用数据库配置配置您的 DataSource.groovy。

然后定义一个Domain类:

Class Seq{

    int seq

}

并在服务中使用动态查找器:

Class SeqService {

    String findAndModify(String seq_name) {
        def seqInstance = Seq.get(seq_name)
        if(seqInstance){
            seqInstance.seq ++
            seqInstance.save()
            return seqInstance.seq.toString()
        }
        return ''      //instance not found
    }
}

然后在您需要该操作时拨打电话:

def seqService

def id
.......
def result = seqService.findAndModify(id)
....
于 2012-12-23T16:32:32.610 回答