PageRenderTime 75ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/scala/br/com/gfuture/mongodbhelper/Query.scala

https://github.com/josa/mongodb-scala-helper
Scala | 74 lines | 49 code | 10 blank | 15 comment | 1 complexity | e0a8d1e0271c332dd1740f65a37eedb4 MD5 | raw file
  1. package br.com.gfuture.mongodbhelper
  2. import mongodb.MongoProvider
  3. import collection.mutable.Builder
  4. import com.mongodb.casbah.commons.{Imports, MongoDBObject}
  5. import org.slf4j.LoggerFactory
  6. import com.mongodb.{DBCursor, DBCollection}
  7. /**Interface de consulta no solr
  8. *
  9. * by Jeosadache Galvão, josa.galvao@gmail.com
  10. */
  11. class Query(val documentClass: Class[_ <: Document]) {
  12. private lazy val logger = LoggerFactory.getLogger(getClass)
  13. val queryBuilder = MongoDBObject.newBuilder
  14. /**Retorna a lista de resultados
  15. */
  16. def resultList: List[Document] = {
  17. val listBuilder: Builder[Document, List[Document]] = List.newBuilder[Document]
  18. val cursor: DBCursor = collection.find(queryBuilder.result)
  19. while (cursor.hasNext) listBuilder += DocumentTools.fromMongoObject(cursor.next, documentClass)
  20. val list: List[Document] = listBuilder.result
  21. logger.isDebugEnabled() match {
  22. case true =>
  23. logger.debug("find %s query[%s], %s itens encontrados".format(documentClass.getSimpleName, cursor.getQuery.toString, cursor.size))
  24. list.size match {
  25. case 0 =>
  26. case _ =>
  27. logger.debug("documents found:")
  28. list.foreach({
  29. entity => logger.debug(entity.toString)
  30. })
  31. }
  32. }
  33. list
  34. }
  35. /**Retorna um resultado para a busca
  36. */
  37. def uniqueResult: Document = {
  38. val dbObject: Imports.DBObject = queryBuilder.result
  39. val entity = DocumentTools.fromMongoObject(collection.findOne(dbObject), documentClass)
  40. logger.isDebugEnabled() match {
  41. case true =>
  42. logger.debug("find unique query[%s]" format (dbObject.toString))
  43. entity match {
  44. case e: Document =>
  45. logger.debug("document found: %s" format (entity.toString))
  46. case _ =>
  47. logger.debug("document not found")
  48. }
  49. }
  50. entity
  51. }
  52. /**Adiciona a clausula na query
  53. *
  54. * @param o field
  55. * @param o valor do field
  56. */
  57. def addClause(field: String, value: Any): Query = {
  58. queryBuilder += field -> value
  59. this
  60. }
  61. /**Recupera a coleção do documento
  62. */
  63. private def collection: DBCollection = MongoProvider.getCollection(documentClass)
  64. }