How to handle null in Anorm

倖福魔咒の 提交于 2019-12-05 20:17:55

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 *)

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!