如何在 Anorm 和 Play Framework 中使用可空列?

发布于 2024-11-29 10:23:15 字数 663 浏览 5 评论 0原文

我有一个案例类 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?

我尝试过:

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))
     }
}

如果列data为空,我想要None,否则我想要Some(data)作为案例类中的remindMe。是的,上面的Scala代码是非常错误的,但我不明白如何解决这个问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

皓月长歌 2024-12-06 10:23:15

这应该可以工作,因为您已经定义了选项:

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)

     }
}

您粘贴的情况将忽略所有 None 结果,因为它们与 Some(data) 不匹配

编辑:在末尾添加“toList”可以解决它,正如@kassens所说。我在 Play 1.2.2-Scala 0.91 环境中测试了它。有办法给他积分吗? :)

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? :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文