【问题标题】:[RuntimeException: SqlMappingError(No rows when expecting a single one)][RuntimeException: SqlMappingError(No rows when expecting a single one)]
【发布时间】:2013-03-08 10:59:17
【问题描述】:

有没有办法让 Scala Anorm 处理空行结果?

我刚刚收到这个错误:[RuntimeException: SqlMappingError(No rows when expecting one one)]

我的方法:

def findByEmail(email: String): User = {
      DB.withConnection { implicit connection=>
        SQL("SELECT * FROM users WHERE email = {email}").on(
          'email  -> email
          ).as(User.simple.single)
      }
}

【问题讨论】:

  • 您应该使用 singleOpt 而不是 single。并返回 Option[User] 而不是 User。

标签: mysql scala playframework-2.0 anorm


【解决方案1】:

你就快到了,不需要使用单打和奇怪的大小写匹配。只需这样做:

def findByEmail(email: String): Option[User] = {
  DB.withConnection { implicit connection=>
    SQL("SELECT * FROM users WHERE email = {email}").on(
      'email  -> email
      ).as(User.simple.singleOpt)
  }
}

【讨论】:

    【解决方案2】:

    如果有人遇到这个错误,这就是我解决地雷的方法:

       def findByEmail(email: String): User = {
            DB.withConnection { implicit connection=>
              val query = SQL("SELECT * FROM users WHERE email = {email}").on(
                'email  -> email
              )
              simple.single(query()) match {
                  case Success(user) => user
                  case Error(e) => null
              }
            }
        }
    

    您可以将案例设置为任何内容

    【讨论】:

    • 不返回空值。请改用 scala 选项。
    • Anorm 为您返回 Optionals 处理空值,在可以避免它们时使用空值不是一个好习惯。
    猜你喜欢
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2022-12-02
    • 2022-12-02
    • 1970-01-01
    • 2022-12-01
    • 2022-12-26
    相关资源
    最近更新 更多