如何在scala中使用play框架获取Mysql的结果总和?

时间:2013-10-31 10:31:53

标签: mysql scala playframework playframework-2.1 anorm

我正在处理简单的scala web应用程序,我正在运行查询,然后播放应用程序正在提供异常

[RuntimeException:UnexpectedNullableFound(ColumnName(.SUM(score),Some(SUM(score)))))]

play.api.Application$$anon$1: Execution exception[[RuntimeException: UnexpectedNullableFound(ColumnName(.SUM(score),Some(SUM(score))))]]
    at play.api.Application$class.handleError(Application.scala:289) ~[play_2.10.jar:2.1.2]
    at play.api.DefaultApplication.handleError(Application.scala:383) ~[play_2.10.jar:2.1.2]
    at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$18$$anonfun$apply$18.apply(PlayDefaultUpstreamHandler.scala:310) ~[play_2.10.jar:2.1.2]
    at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$18$$anonfun$apply$18.apply(PlayDefaultUpstreamHandler.scala:308) ~[play_2.10.jar:2.1.2]
    at play.api.libs.concurrent.PlayPromise$$anonfun$extend1$1.apply(Promise.scala:113) ~[play_2.10.jar:2.1.2]
    at play.api.libs.concurrent.PlayPromise$$anonfun$extend1$1.apply(Promise.scala:113) ~[play_2.10.jar:2.1.2]
Caused by: java.lang.RuntimeException: UnexpectedNullableFound(ColumnName(.SUM(score),Some(SUM(score))))
    at scala.sys.package$.error(package.scala:27) ~[scala-library.jar:na]
    at anorm.Sql$.as(Anorm.scala:535) ~[anorm_2.10.jar:2.1.2]
    at anorm.Sql$class.as(Anorm.scala:453) ~[anorm_2.10.jar:2.1.2]
    at anorm.SimpleSql.as(Anorm.scala:370) ~[anorm_2.10.jar:2.1.2]
    at models.Keyword$$anonfun$getBlogScore$1.apply(Keyword.scala:53) ~[na:na]
    at models.Keyword$$anonfun$getBlogScore$1.apply(Keyword.scala:52) ~[na:na]

模型/ keyword.scala

def getBlogScore(word: String, blog: String): Long={DB.withConnection{implicit c=>
 SQL("select SUM(score) from keyword where blog like {blog} and word = {word}").on('blog->blog,'word->word).as(scalar[Long].single)
}
}

我希望根据某些条件得到总分列。

给我一​​些解决这个例外的想法!

3 个答案:

答案 0 :(得分:1)

尝试:

SQL("select SUM(score) from keyword where blog like {blog} and word = {word}").
  on('blog->blog,'word->word).
  as(scalar[Option[Long]].single).
  getOrElse(0L)

答案 1 :(得分:0)

当没有匹配的行时,我猜SUM会返回NULL。我也在猜测 在这种情况下你可能想要0

所以你必须处理这种情况。我想起了Option。快速查看文档,点击Option表示有.singleOpt

所以你可以试试:

def getBlogScore(word: String, blog: String): Long = 
  DB.withConnection { implicit c =>
    SQL("select SUM(score) from keyword where blog like {blog} and word = {word}").
      on('blog->blog,'word->word).
      as(scalar[Long].singleOpt).
      getOrElse(0L)
  }

答案 2 :(得分:0)

稍微迟了但Anorm master分支中修复了这个问题:https://github.com/playframework/playframework/pull/2072