Skip to content

Instantly share code, notes, and snippets.

@rktoomey
Forked from anonymous/TestNesting.scala
Created May 14, 2012 02:50
Show Gist options
  • Save rktoomey/2691508 to your computer and use it in GitHub Desktop.
Save rktoomey/2691508 to your computer and use it in GitHub Desktop.
Salat nested case class with scala 2.9.1
rose@marzipan:~/workspace/salat (master)$ sbt
salat:master:0.0.8-SNAPSHOT> project salat-core
[info] Set current project to salat-core (in build file:/home/rose/workspace/salat/)
salat-core:master:0.0.8-SNAPSHOT> test:console
scala> import com.mongodb.casbah._
import com.mongodb.casbah._
scala> import com.novus.salat.grater
import com.novus.salat.grater
scala> import com.novus.salat.annotations._
import com.novus.salat.annotations._
scala> import com.novus.salat.global._
import com.novus.salat.global._
scala> import com.mongodb.casbah.Implicits._
import com.mongodb.casbah.Implicits._
scala> import hugh.model._
import hugh.model._
scala> val child = Child("C")
child: hugh.model.Child = Child(C)
scala> val parent = Parent("testId", child)
parent: hugh.model.Parent = Parent(testId,Child(C))
scala> grater[Child].asDBObject(child)
res0: com.mongodb.casbah.Imports.DBObject = { "_typeHint" : "hugh.model.Child" , "value" : "C"}
scala> grater[Parent].asDBObject(parent)
res1: com.mongodb.casbah.Imports.DBObject = { "_typeHint" : "hugh.model.Parent" , "_id" : "testId" , "nested" : { "_typeHint" : "hugh.model.Child" , "value" : "C"}}
package hugh.demo
import com.mongodb.casbah._
import com.novus.salat.grater
import com.novus.salat.annotations._
import com.novus.salat.global._
import com.mongodb.casbah.Implicits._
import hugh.model._
// hey, check out SalatDAO at https://github.com/novus/salat/wiki/SalatDAO
object TestNesting {
def main(args: Array[String]) {
val db = MongoConnection()("childtest")
val coll = db("testColl")
coll.drop
val child = Child("C")
val parent = Parent("testId", child)
// A conversion straight back to Parent will work here as the DBObject has
// the Child, not a DBObject of the child
println(grater[Parent].asDBObject(parent))
// On save, the Child class gets flattened to a DBList because
// it implements Product
coll.save(grater[Parent].asDBObject(parent))
coll.findOneByID("testId") map { result =>
// This row will cause an error as it expects type "Child" and receives
// A db list [ "C" ]
println(grater[Parent].asObject(result))
}
}
}
package hugh.model
import com.mongodb.casbah._
import com.novus.salat.grater
import com.novus.salat.annotations._
import com.novus.salat.global._
import com.mongodb.casbah.Implicits._
case class Child(value: String)
case class Parent(@Key("_id") id: String, nested: Child)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment