-->

How to handle null in Anorm

2019-05-10 04:42发布

问题:

I have a table with nullable column, and when query the null column, it threw error

 val row: List[(String,String)] = SQL("select top 10 Spare_Part part,Pricing_Category cat from Price_Point_Base")
                .as((str("part"))~ str("cat") map(flatten) *)

I checked the link https://www.playframework.com/documentation/2.0/ScalaAnorm .

It only gives away to handle nullable column using something like

SQL("Select name,indepYear from Country")().map { row =>
  row[String]("name") -> row[Option[Int]]("indepYear")
}

But since str("part") is more compact than row[String]("name"), so I'd like to try using str("part"), but how to make str("part") works with nullable column?

回答1:

If you're reading a nullable column, you really should be binding it to an Option[String] to represent that it could be missing a value. Anorm will not convert it to null, rather it will throw an error.

val row: List[(Option[String], String)] = 
    SQL("select top 10 Spare_Part part,Pricing_Category cat from Price_Point_Base")
       .as( get[Option[String]("part") ~ str("cat") map(flatten) *)

This is messy however, and would get messier if you wanted to supply a default value for the String. We could make a re-usable parser that defaults NULL values to empty strings:

val parser: RowParser[(String, String)] = {
    get[Option[String]]("part") ~ get[Option[String]]("cat") map {
       case part~cat => (part.getOrElse(""), cat.getOrElse(""))
    }
}

And then apply it:

val row: List[(String, String)] = 
    SQL("select top 10 Spare_Part part,Pricing_Category cat from Price_Point_Base")
       .as(parser *)


回答2:

If you look here you'll see there is nothing that you're looking for. But looking at the source code I can assume that you can implement it yourself like this:

def strOpt(columnName: String)(implicit c: Column[Option[String]]): RowParser[Option[String]] =
  get[Option[String]](columnName)(c)

Didn't test it though but should likely work fine.



标签: scala anorm