Question

Is there a way that I can get Scala Anorm to hanlde empty row results?

I just get this error: [RuntimeException: SqlMappingError(No rows when expecting a single one)]

My method:

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

Solution

You were almost there, don't need to use singles and weird case matching. Just do this:

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

OTHER TIPS

If anyone ever runs into this error this is how I solved mines:

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

You can set the cases to whatever

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top