salat库映射mongodb数据到CaseClass

date
Jun 3, 2021
slug
salat-mapping-problem
status
Published
tags
问题记录
summary
type
Post
读书笔记
 

添加库依赖

在sbt.build中添加以下的依赖
resolvers ++= Seq(
  "repo.novus rels" at "http://repo.novus.com/releases/",
  "Sonatype OSS" at "https://oss.sonatype.org/content/repositories/releases"
)
libraryDependencies ++= Seq(
  "org.mongodb" %% "casbah" % "2.7.0",
  "com.novus" %% "salat" % "1.9.7"
)

Insert

import com.mongodb.casbah.Imports._
import com.novus.salat._
import com.novus.salat.global._
case class User(uid:String, provider:String, age:Int)
object Sample extends App {
  //获得test_collection集合
  val col = DB.get().getCollection("test_collection")
  val userObj = grater[User].asDBObject(User("Azalea", "Facebook", 30))
  val result = col.insert(userObj)
  println(result)
}

Find

   val result = col.find()
  import scala.collection.JavaConversions._
  result.iterator().foreach(dbo => {
    println(grater[User].asObject(dbo))
  })

如果CaseClass中设置了null值会怎么样呢?

val col = DB.get().getCollection("test_collection")
  val userObj = grater[User].asDBObject(User("Azalea", null, 30))
  val tgt     = MongoDBObject("uid" -> "Azalea")
  println(col.update(tgt, userObj))
  val result = col.findOne(tgt)
  println(s"Result : $result")
  println(grater[User].asObject(result))
可以看到报错了
{ "serverUsed" : "/127.0.0.1:27017" , "updatedExisting" : true , "n" : 1 , "connectionId" : 3 , "err" :  null  , "ok" : 1.0}
Result : { "_id" : { "$oid" : "529319fa0cf2b37a655f3a07"} , "uid" : "Azalea" , "age" : 30}
[error] (run-main) java.lang.Exception: class models.connections.User requires value for 'provider'
java.lang.Exception: class models.connections.User requires value for 'provider'
    at com.novus.salat.DefaultArg.safeValue$lzycompute(Grater.scala:418)
    at com.novus.salat.DefaultArg.safeValue(Grater.scala:414)
    at com.novus.salat.ConcreteGrater.safeDefault(Grater.scala:375)
provider字段必须要填写,不写不行,咋办呢。我们修改下CaseClass
case class User(uid:String, provider:Option[String], age:Int)
把provider字段改成了Option类型,然后修改下更新操作
val col = DB.get().getCollection("test_collection")
  val userObj = grater[User].asDBObject(User("Azalea", None, 30))
  val tgt     = MongoDBObject("uid" -> "Azalea")
  println(col.update(tgt, userObj))
  val result = col.findOne(tgt)
  println(grater[User].asObject(result))
在构建User对象的时候用了None,而不是null,看下结果
{ "serverUsed" : "/127.0.0.1:27017" , "updatedExisting" : true , "n" : 1 , "connectionId" : 4 , "err" :  null  , "ok" : 1.0}
Result : { "_id" : { "$oid" : "529319fa0cf2b37a655f3a07"} , "uid" : "Azalea" , "age" : 30}
User(Azalea,None,30)
[success] Total time: 15 s, completed 2013/11/25 18:53:13
成功更新了。所以在scala中尽量避免使用null,使用none是极好的。

© Frandy 2024