开发者

How to use nullable columns with Anorm and Play Framework?

I have a case class MyRecord that I want to use for every row in a resultset:

case class MyRecord开发者_开发问答(id: Int, remindeMe: Option[org.joda.time.DateTime])

How do I SELECT all rows in a table and return a List of MyRecord using Scala and Anorm with Play Framework?

I have tried with:

def getRecords() : List[MyRecord] = {
      val records = SQL("SELECT id, data FROM mytable")().collect {
          case Row(id: Int, Some(data: Long)) => 
                      MyRecord(id, new org.joda.time.DateTime(data))
     }
}

If the column data is null I want None otherwise I want Some(data) as remindMe in the case class. Yes, the above Scala code is very wrong, but I don't understand how to solve this.


This should work as you have already defined the Option:

def getRecords() : List[MyRecord] = {
      SQL("SELECT id, data FROM mytable")().collect {
          case Row(id: Int, Some(data: Long)) => 
                  MyRecord(id, Some(new org.joda.time.DateTime(data)))
          case Row(id: Int, None) => 
                  MyRecord(id, None)

     }
}

The case that you paste would ignore all the None results as they would not match Some(data)

EDIT: adding the "toList" at the end solves it, as @kassens said. I tested it in a Play 1.2.2-Scala 0.91 env. There's a way to give the points to him? :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜