0

I am looking to implement my DAO access layer using Scala 2.9.x and Casbah. Given my entity is a case class with parameters:

case class Price (Id: Option[String], Price: Double, ItemName: String)

and my BSON document looks like:

{
    "_id" : ObjectId("55dd1874b46f7178c8ddb737"),
    "ItemName" : "Beet",
    "Price" : "6"
}

I try to create a property

  override var prices: List[Price] =
    db("prices").find.toList.map(
      o => Price(Some(o("_id").toString),
      o("Price").toString.toDouble,
      o.getAs[String]("ItemName").get ))

Here are my main concerns: 1. Mapping fields looks a little cumbersome, there should be some automation for that. I know I can use parser from import net.liftweb.json.{DefaultFormats, Serialization} or any other but I am pretty sure there should be something closer related to Casbah. May be it can be some other MongoDB Scala ORM. 2. I do not like the idea of putting that to var. What is the better way of exposing data? Should I use property? 3. What is the best practice for entites (as you can see I use case class with parameters without any body)

grimcoder
  • 87
  • 6

1 Answers1

2

I'm using Salat for this: https://github.com/salat/salat/wiki/Quick-start

For saving, you use asDBObject to convert a case class.

val testCaseClass = new TestCaseClass(null, "testName", 30, addressList)
collection.save(grater[TestCaseClass].asDBObject(testCaseClass))

For fetching, use asObject instead

val savedCaseClass=grater[TestCaseClass].asObject(collection.findOne().get)

Here's the definition of the case class

class TestCaseClass(_id:ObjectId, name:String, age:Int, address:List[AddressCase])
waterscar
  • 876
  • 1
  • 8
  • 14
  • Gave Salat a try and now I am having a different error: `case class Sale (@Key("_id") Id: Option[String], Date: Date, SaleDetails: List[SaleDetail]) ` my json : `{ "_id" : ObjectId("55f13d293aab21313e576d34"), "Date" : "2015-06-24T22:22:33.875Z", "SaleDetails" : [ { "ItemName" : "Carrots", "Price" : 1.6000000000000001, "Units" : 9 } ] }` I am trying to read sales: `override var sales: List[Sale] = db("sales").find.toList.map( obj => grater[Sale].asObject(obj))` an error: argument type mismatch – grimcoder Sep 11 '15 at 05:04
  • I always use type ObjectId for the _id field of a case class. Here's my testCaseClass's definition `case class TestCaseClass(_id:ObjectId, name:String, age:Int, address:List[AddressCase])` – waterscar Sep 11 '15 at 06:48
  • Using ObjectId for the model makes this class MongoDB - specific which is not good because I do not want my business and/or UI layer to be aware of the details of persistence. – grimcoder Sep 11 '15 at 07:30
  • It is possible to use UUID instead, check this test case from Salat on how to work with it: https://github.com/salat/salat/blob/master/salat-core/src/test/scala/com/novus/salat/test/UUIDSupportSpec.scala – waterscar Sep 11 '15 at 07:34