Created
April 1, 2013 11:46
-
-
Save tgpfeiffer/5284513 to your computer and use it in GitHub Desktop.
A Lift helper class to generate sequential long values when using MongoDB with Record.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package code.model | |
import net.liftweb.mongodb.BsonDSL._ | |
import net.liftweb.record.field._ | |
import net.liftweb.util.Helpers._ | |
import net.liftweb.common._ | |
import net.liftweb.mongodb.record._ | |
import field._ | |
import com.mongodb.{DBObject, BasicDBObject} | |
class MongoSequence extends MongoRecord[MongoSequence] with ObjectIdPk[MongoSequence] with Loggable { | |
def meta = MongoSequence | |
object name extends StringField(this, 100) | |
object value extends LongField(this) | |
} | |
object MongoSequence extends MongoSequence with MongoMetaRecord[MongoSequence] { | |
// unique index | |
ensureIndex(("name" -> 1), ("unique" -> true)) | |
def getNextValue(which: String): Long = { | |
useColl { | |
coll => | |
val finder: DBObject = new BasicDBObject("name", which) | |
val upd: DBObject = new BasicDBObject("$inc", new BasicDBObject("value", 1)) | |
val res = coll.findAndModify(finder, null, null, false, upd, true, true) | |
if (res.containsField("value")) | |
asLong(res.get("value")).getOrElse(1L) | |
else | |
1L | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment