【问题标题】:Scala Slick - Omit ID column (Auto_Increment)Scala Slick - 省略 ID 列 (Auto_Increment)
【发布时间】:2017-08-15 06:12:34
【问题描述】:

我学习了 Scala、Slick、Akka 2 个月,在做 Akka 的项目时遇到了问题......

// This case class is to use for parsing data from request
// case class UserTransaction(sender: String, recipient: String, amount: Int)

//This one is to use for reflecting database
case class UserTransactionDB(sender: String, recipient: String, amount: Int, id: Int)

class UserTransactionModelDB(tag: Tag) extends Table[UserTransactionDB](tag, "usertransaction")
{
    def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
    def sender = column[String]("sender")
    def recipient = column[String]("recipient")

    def amount = column[Int]("amount")

    override def * =

        (sender, recipient, amount, id) <> (UserTransactionDB.tupled, UserTransactionDB.unapply)

}

我想像这样向 Akka 发送一个 POST 请求(Json):

{"sender" : "S" , "recipient" : "R", "amount" : 100}

现在,我只想使用一个案例类 UserTransaction(在 UserTransactionDB 中没有“id”字段),不仅可以反映数据库,还可以解析请求中的数据。这可能吗?

谢谢你,对不起我的英语!

【问题讨论】:

  • 你用的是什么 json 库?我假设spray-json... 在这种情况下,您可以提供一个spray-json 序列化程序来摆脱id 字段。
  • @mfirry 是的,我正在使用 jsonFormat4(UserTransactionDB.apply)
  • @mfirry 你是说这个吗? github.com/spray/…
  • 谢谢,我做到了:)

标签: scala akka slick


【解决方案1】:

尝试使用自定义格式...类似以下内容:

case class UserTransactionDB(sender: String, recipient: String, amount: Int, id: Int)

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit object UserTransactionJsonFormat extends RootJsonFormat[UserTransactionDB] {
    def write(c: UserTransactionDB) =
      JsArray(JsString(c.sender), JsString(c.recipient), JsNumber(c.amount))

    def read(value: JsValue) = value match {
      case JsArray(Vector(JsString(sender), JsString(recipient), JsNumber(amount))) =>
        new UserTransactionDB(sender, recipient, amount.toInt)
      case _ => deserializationError("UserTransactionDB expected")
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多