PageRenderTime 25ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/scala/dsbw/mongo/MongoDAO.scala

https://bitbucket.org/marcromera/dsbw-1213t
Scala | 61 lines | 45 code | 16 blank | 0 comment | 2 complexity | 7ec96337fbe1042491b1d60b66f20d4d MD5 | raw file
  1. package dsbw.mongo
  2. import com.mongodb.casbah.MongoCollection
  3. import com.novus.salat.dao.SalatDAO
  4. import org.bson.types.ObjectId
  5. import com.mongodb.casbah.Imports._
  6. import com.mongodb.MongoException.DuplicateKey
  7. import com.novus.salat.Context
  8. import com.mongodb.casbah.commons.MongoDBObject
  9. import dsbw.mongo.SalatContext.ctx
  10. class MongoDao[ObjectType <: AnyRef](collection: MongoCollection)(implicit mot: Manifest[ObjectType]) {
  11. val salatDao = new SalatDAO[ObjectType,ObjectId](collection){}
  12. def checkLastError() {
  13. val lastError = collection.getLastError()
  14. try{
  15. lastError.throwOnError()
  16. }catch{
  17. case m:DuplicateKey => {
  18. val errorMsg = lastError.getString("err")
  19. val index = collection.indexInfo.find(ii => (ii.get("unique") == true) && errorMsg.contains("%s.$%s".format(ii.get("ns"),ii.get("name"))))
  20. index.map(ii => throw new DuplicateKeyException(collection.name,ii.get("name").asInstanceOf[String]))
  21. throw m
  22. }
  23. case t:Throwable => throw t
  24. }
  25. }
  26. def findOne[T<: AnyRef](query:Map[String,T]): Option[ObjectType] = salatDao.findOne(query)
  27. def findOneByID(id:ObjectId): Option[ObjectType] = salatDao.findOneByID(id)
  28. def findByIds(ids:Set[ObjectId]) = salatDao.find("_id" $in ids).toSet
  29. def findAll = salatDao.find((MongoDBObject.empty))
  30. def update[T<: AnyRef](query:Map[String,T],update:MongoDBObject,multi:Boolean=true) {
  31. salatDao.update(query,update,multi=multi)
  32. }
  33. def updateById(id:ObjectId,update:MongoDBObject){
  34. this.update(Map("_id"->id),update,multi=false)
  35. }
  36. def updateByIds(ids:Set[ObjectId],update:MongoDBObject){
  37. salatDao.update("_id" $in ids,update,multi=true)
  38. }
  39. def save(obj:ObjectType) {
  40. salatDao.save(obj)
  41. }
  42. }
  43. case class DuplicateKeyException(collection:String, key:String) extends RuntimeException{
  44. override def toString = """DuplicateKeyException(collection="%s",key="%s")""".format(collection,key)
  45. }