如何在 Anorm 和 Play Framework 中使用可空列?
我有一个案例类 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以工作,因为您已经定义了选项:
您粘贴的情况将忽略所有 None 结果,因为它们与 Some(data) 不匹配
编辑:在末尾添加“toList”可以解决它,正如@kassens所说。我在 Play 1.2.2-Scala 0.91 环境中测试了它。有办法给他积分吗? :)
This should work as you have already defined the Option:
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? :)