变量列数量Anorm结果集解析器

时间:2016-05-06 19:36:26

标签: scala anorm

我正在尝试使用scala,这是我的堆栈:

  • Windows 10
  • JDK 1.8
  • Scala 2.11.8
  • PlayFramework 2.5
  • Anorm 2.4.0
  • MySQL的               5.5

我想用Anorm创建一个结果集解析器,它能够解析我从给定表中选择的任意数量的列。这是我的代码:

case class Campaign(id: Int, campaign_mode_id: Int, name: String)

class Application @Inject()(db: Database) extends Controller {

  val campaign = {
    get[Int]("campaign.id") ~
    get[Int]("campaign.campaign_mode_id") ~
    get[String]("campaign.name") map {
      case id ~ campaign_mode_id ~ name  => Campaign(id, campaign_mode_id, name)
    }
  }

  def index = Action {
    val data : List[Campaign] = db.withConnection { implicit connection =>
      SQL("SELECT id, campaign_mode_id, name FROM campaign").as(campaign.*)
    }

    Ok(views.html.index(data))
  }
} 

我希望能够运行以下Sqls并仍然使用相同的case class Campaign

SELECT id, name FROM campaign
SELECT name FROM campaign

如何实现此功能?

更新

我将某些字段的代码更改类型更新为选项:

case class Campaign(id: Int, campaign_mode_id: Option[Int], name: Option[String])

class Application @Inject()(db: Database) extends Controller {

  val campaign = {
    get[Int]("campaign.id") ~
    get[Option[Int]]("campaign.campaign_mode_id") ~
    get[Option[String]]("campaign.name") map {
      case id ~ campaign_mode_id ~ name  => Campaign(id, campaign_mode_id, name)
    }
  }

  def index = Action {
    val data : List[Campaign] = db.withConnection { implicit connection =>
      SQL("SELECT id, name FROM campaign").as(campaign.*)
    }

    Ok(views.html.index(data))
  }
}

此代码产生以下错误:

[RuntimeException: campaign.campaign_mode_id not found, available columns : campaign.id, id, campaign.name, name]

1 个答案:

答案 0 :(得分:1)

如果列campaign_mode_id可以为空,则解析为Option[Int]并且始终存在于结果集中,请使用:

get[Option[Int]]("campaign.campaign_mode_id")

如果列campaign_mode_id不可为空,可能不会出现在结果集中,并解析为Option[Int],请使用:

get[Int]("campaign.campaign_mode_id").?

在您的情况下,您似乎想要:

val campaign = {
  get[Int]("campaign.id") ~
  get[Int]("campaign.campaign_mode_id").? ~
  get[String]("campaign.name").? map {
     case id ~ campaign_mode_id ~ name  => Campaign(id, campaign_mode_id, name)
  }
}

这假定campaign.campaign_mode_idcompaign.name都是非可空的,但在结果集中是可选的。