简体   繁体   English

如何在 Anorm 和 Play 框架中使用可为空的列?

[英]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:我有一个案例 class MyRecord 我想用于结果集中的每一行:

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?如何 SELECT 表中的所有行并使用 Scala 和 Anorm 与 Play Framework 返回 MyRecord 列表?

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.如果列data是 null 我想要None否则我想要Some(data)作为提醒我在 class 的情况下。 Yes, the above Scala code is very wrong, but I don't understand how to solve this.是的,上面的Scala代码很不对,但是我不明白怎么解决。

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)您粘贴的情况将忽略所有 None 结果,因为它们与 Some(data) 不匹配

EDIT: adding the "toList" at the end solves it, as @kassens said.编辑:正如@kassens 所说,在最后添加“toList”可以解决它。 I tested it in a Play 1.2.2-Scala 0.91 env.我在 Play 1.2.2-Scala 0.91 环境中对其进行了测试。 There's a way to give the points to him?有办法给他加分吗? :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM