如何使用Scala Slick访问一行中的数据库条目



我使用以下教程中的代码:sysgears.com/articles/building-rest-service-with-scala/# 16

我的数据库模式:

    /**
     * Customer entity.
     *
     * @param id        unique id
     * @param firstName first name
     * @param lastName  last name
     * @param accountBalance account balance
     * @param birthday  date of birth
     */
     case class Customer(id: Option[Long], firstName: String, lastName: String, accountBalance: Int, birthday: Option[java.util.Date])
     /**
      * Mapped customers table object.
      */
     object Customers extends Table[Customer]("customers") {
       def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
       def firstName = column[String]("first_name")
       def lastName = column[String]("last_name")
       def accountBalance = column[Int]("account_balance")
       def birthday = column[java.util.Date]("birthday", O.Nullable)
       def * = id.? ~ firstName ~ lastName ~ accountBalance ~ birthday.? <>(Customer, Customer.unapply _)
       implicit val dateTypeMapper = MappedTypeMapper.base[java.util.Date, java.sql.Date](
       {
        ud => new java.sql.Date(ud.getTime)
       }, {
         sd => new java.util.Date(sd.getTime)
       })
       val findById = for {
         id <- Parameters[Long]
         c <- this if c.id is id
       } yield c
     }

我正在编写一个函数,用于检索具有指定id号的Customer。然后我想访问这个客户的帐户余额并对其进行计算。

这是我到目前为止的代码:

     def withdraw(id: Long, amountToWithdraw: Long): Either[Failure, Customer] = {
         try {
           db.withSession {
            val customerRow = Customers.filter{ a => a.id === id}
            var amount = customerRow.accountBalance
             if (amountToWithdraw < accountBalance){
                accountBalance -= amountToWithdraw
                    update(customerId, customer)
                Right(customer)
             }
             else{
                 Left(insufficientFundsError(id))
                }
          }  
         } catch {
           case e: SQLException =>
             Left(databaseError(e))
         }
       }

当我尝试运行它时,我得到一个错误:

    value accountBalance is not a member of scala.slick.lifted.Query[com.sysgears.example.domain.Customers.type,scala.slick.lifted.NothingContainer#TableNothing]
    var amount = customerRow.accountBalance
                             ^

所以我想我的问题是我不知道如何访问数据库条目accountBalance为指定的客户?

我实际上并不需要提取任何客户。我只需要提取具有指定id的客户的accountBalance的值。我是这样做的:

    val accBal = Customers.filter{ a => a.id === id}.map(_.accountBalance).firstOption

因为accBal的类型是Option[Long]我不得不:

    val accBalAsLong: Long = accBal.getOrElse(0)

Slick就像Scala集合。Customers就像一个集合。I没有元素accountBalance,只有它的元素有。所以必须用.map。或者在您的情况下,可能更容易立即获取客户记录。

val customerRow = Customers.filter{ a => a.id === id}.run.head

最新更新