如何在 Anorm 中处理 null [英] How to handle null in Anorm

查看:59
本文介绍了如何在 Anorm 中处理 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含可为空列的表,当查询空列时,它抛出错误

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

我检查了链接https://www.playframework.com/documentation/2.0/ScalaAnorm .

它只会使用诸如

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

但是由于 str("part")row[String]("name") 更紧凑,所以我想尝试使用 str("part"),但是如何使 str("part") 与可空列一起工作?

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?

推荐答案

如果您正在读取可为空的列,您真的应该将其绑定到 Option[String] 表示它可能缺少一个值.Anorm 不会将其转换为 null,而是会抛出错误.

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

然而,这很混乱,如果您想为 String 提供默认值,则会变得更加混乱.我们可以制作一个可重用的解析器,将 NULL 值默认为空字符串:

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(""))
    }
}

然后应用它:

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

这篇关于如何在 Anorm 中处理 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆