【问题标题】:Select from RDBMS using Anorm and Play 2.2 for Scala使用 Anorm 和 Play 2.2 for Scala 从 RDBMS 中选择
【发布时间】:2013-10-20 11:32:06
【问题描述】:

为了使用 Anorm 从表中检索一行,我已记下此代码,但出现错误。代码如下:

case class UserInquiry(
    id:Long, description:String
)

object UserInquiry {
   val byIdStmt = """
      SELECT id, description FROM user_inquiry WHERE id = {id}
   """

   def findById(id: Long) = {
      DB.withConnection { implicit conn =>
         SQL(byIdStmt).on("id" -> id).apply().collect {  
            case Row(Some(id:Integer), Some(description:String)) => 
            new UserInquiry(id.toLong, description)
         }.head
      }    
   }
}

// This gives me an error
val id = UserInquiry.findById(7) 

这是错误:

[MatchError: Row('ColumnName(user_inquiry.id,Some(id))':4 as java.lang.Integer,
'ColumnName(user_inquiry.description,Some(description))':My search as java.lang.String)
(of class anorm.SqlRow)]

如果我从 SQL 语句中删除“id”列,并从代码中删除它的引用,以便只获取名为“description”的列,那么一切正常。

“id”列有什么问题?如果它是 java.lang.Integer 列,为什么不匹配?是否有特定于 DB 'Primary Keys' 的类?

【问题讨论】:

  • 检查您是否使用了正确的数据库。你也可以先调用head(),然后再使用map。我怀疑它会让它工作,但你应该这样做而不是收集。我从未使用过 Anorm,但我觉得这样做是对的:p
  • 感谢您的提示,但没有成功。关于数据库,我连接到我配置的唯一一个。不过,INSERTS 和 UPDATES 可以正常工作。
  • 似乎 id 被映射到一个字符串...
  • 你在哪里可以看到??错误消息说:4 java.lang.Integer
  • @Max,您能否提供解决方案,说明您如何仅获得名为:您的问题的“描述”值的列,因为我有类似的问题。

标签: scala playframework-2.0 anorm


【解决方案1】:

好的,我知道错了:

作为'id'列一个PK,下面这行代码

case Row(Some(id:Integer), Some(description:String)) 

必须改成:

case Row(id:Integer, Some(description:String)) 

这是因为PK列不能为NULL,所以不希望使用Option[T]对象来封装从DB检索到的值。

【讨论】:

    猜你喜欢
    • 2015-10-04
    • 1970-01-01
    • 2013-10-21
    • 2013-03-13
    • 2014-03-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多