Created
November 12, 2010 04:05
-
-
Save maxaf/673709 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_20). | |
Type in expressions to have them evaluated. | |
Type :help for more information. | |
scala> import com.mongodb.casbah.Imports._ | |
import com.mongodb.casbah.Imports._ | |
scala> val conn = MongoConnection() // connect to MongoDB | |
conn: com.mongodb.casbah.MongoConnection = com.mongodb.casbah.MongoConnection@7440d1b0 | |
scala> val db = conn("test_db") // get a database handle | |
db: com.mongodb.casbah.MongoDB = test_db | |
scala> val collection = db("things") // get a collection handle | |
collection: com.mongodb.casbah.MongoCollection = MongoCollection() | |
scala> import com.bumnetworks.casbah.mapper.Mapper // we will extend this class to provide an object/document mapper | |
import com.bumnetworks.casbah.mapper.Mapper | |
scala> import scala.reflect.BeanInfo // need this annotation to generate bean info classes | |
import scala.reflect.BeanInfo | |
scala> import com.bumnetworks.casbah.mapper.annotations._ // mapper annotations that define fields | |
import com.bumnetworks.casbah.mapper.annotations._ | |
scala> @BeanInfo @UseTypeHints case class Thing(@ID val id: ObjectId = new ObjectId, @Key name: String) | |
defined class Thing | |
scala> object ThingMapper extends Mapper[Thing] // define singleton mapper instance | |
defined module ThingMapper | |
scala> val thing1 = Thing(name = "thing 1") // create an instance of mapped case class | |
thing1: Thing = Thing(4cdcbb3f63c3807425ffe296,thing 1) | |
scala> collection.insert(ThingMapper.asDBObject(thing1)) // save it to MongoDB | |
res0: com.mongodb.WriteResult = { "err" : null , "n" : 0 , "ok" : 1.0} | |
scala> val things = collection.find.map(ThingMapper.asObject(_)) // retrieve back all saved objects | |
things: Iterator[Thing] = non-empty iterator | |
scala> val thing2 = things.next // get the first result | |
thing2: Thing = Thing(4cdcbb3f63c3807425ffe296,thing 1) | |
scala> thing2.equals(thing1) // compare it to original - it's the same "thing"! | |
res1: Boolean = true | |
scala> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment