开发者

How to use nullable columns with Anorm and Play Framework?

开发者 https://www.devze.com 2023-03-27 12:54 出处:网络
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])

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

精彩评论

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