当前位置: 首页 > 工具软件 > Casbah > 使用案例 >

mongodb 的 scala 驱动 -> casbah

夏宏旷
2023-12-01

github地址: github.com/1178615156/service

要引的包: “org.mongodb” %% “casbah” % “2.8.1”
web 框架:play
随手封装了下
基本思路:在MongoDao 中实现 镇上查改功能,需要一个隐式参数 用于将 entity 与 DBObject 进行互转
代码
MongoDao—

/**
 * 基于casbah 实现的一个mongo dao
 * @tparam _Value entity value type
 */
abstract class MongoDao[_Value:ClassTag]
{
  type Value =_Value
  import com.mongodb.casbah.Imports._

  /**
   * 链接 mongo 
   */
  lazy val mongoClient  = MongoClient(MongoClientURI.apply(mongoUrl))
  lazy val db           = mongoClient(dbName)
  lazy val collection   = db.getCollection(collectionName)

  //子类可重写
  def mongoUrl:String="mongodb://localhost:27017"
  //子类可重写
  def dbName:String="testdb"

  //在mongo中对应的集合名
  //由子类重写
  def collectionName:String

  /**
   * 查询功能
   * @param mongoDBObject 查询条件
   * @return list 如果 无数据则 list 为 Nil
   */
  def find(mongoDBObject:MongoDBObject=MongoDBObject.empty,
           findParameter: FindParameter=FindParameter.default
            )(implicit read:DBObject=>_Value): List[_Value] ={
    this.collection.
      find(mongoDBObject).
      skip(findParameter.page).limit(findParameter.size).toArray.map(read).toList
  }

  /**
   * 通过Id从数据库中获取对象
   * @param id 查询Id
   * @param read
   * @return
   */
  def getById(id:String)(implicit read:DBObject=>_Value): Option[_Value] =
    this.find(createId(id)).headOption
  /**
   * find 辅助函数
   * @param read
   * @return
   */
  def list(findParameter: FindParameter=FindParameter.default
            )(implicit read:DBObject=>_Value): List[_Value] =
    this.find(findParameter=findParameter)(read)

  /**
   * 保存对象到数据库
   * @param value
   * @param write
   * @return success or failed
   */
  def add(value: _Value)(implicit write:_Value=>DBObject): Try[_Value] ={
    Try{
      this.collection.insert(write(value))
      value
    }
  }

  /**
   *
   * @param id
   * @param read
   * @return
   */
  def remove(id:String)(implicit read:DBObject=>_Value): Try[Option[_Value]] ={
    Try{
      val value=this.find(createId(id)).headOption
      this.collection.remove(createId(id))
      value
    }
  }

  protected def createId(id:String)=MongoDBObject("_id"->new ObjectId(id))
}

MongoImplicitDBObject–

/**
 * 用于将entity 与 DBObject 互转的 工具类
 * @tparam _Value entity value type
 */
class MongoImplicitDBObject[_Value<:EntityId:ClassTag]{
  implicit def EntityToMongoDBObject(entity: _Value): DBObject ={
    if (entity.id isEmpty)
      entity.id=new ObjectId().toString
    val a: Map[String, Any] = entity.ObjToJson.JsonToMap
    val id=a.getOrElse("id","").asInstanceOf[String]
    DBObject(a.-("id").+("_id"->new ObjectId(id)).toList)
  }

  implicit def MongoDBObjectToEntity(dBObject: DBObject): _Value ={
    if (dBObject==null)
      null.asInstanceOf[_Value]
    else{
      val id = dBObject._id.getOrElse("").toString
      dBObject.removeField("_id")
      val a: _Value =dBObject.toString.JsonToObj[_Value]
      a.id=id
      a
    }

  }
  implicit def MongoDBObjectToEntityOpt(dBObject: DBObject): Option[_Value]=
    if (dBObject==null)
      None
    else
      Some(MongoDBObjectToEntity(dBObject))


  def write(entity: _Value): DBObject =EntityToMongoDBObject(entity)
  def read(dBObject: DBObject): _Value =MongoDBObjectToEntity(dBObject)
}

EntityTest

case class EntityTest(
                       @BeanProperty var name:String=""
                       ) extends EntityId
object EntityTest extends MongoImplicitDBObject[EntityTest]
 类似资料: