如何解决RuntimeException:TypeDoesNotMatch(无法将1:类java.lang.String转换为Long for column?

时间:2013-10-30 09:40:45

标签: mysql scala playframework playframework-2.0 playframework-2.1

我正在开发带有scala的play框架的简单web应用程序,并在mysql中存储数据库,我收到错误

Exception

我在做什么:

  • 当用户输入值并在存储后我将用户重定向到显示数据库中存在的所有条目的页面
  • 值已存储,但在重定向到页面时会出现异常

models/Keyword.scala

case class Keyword(blog: String,cat: String,word: String,count: Long, summaryId: String)

object Keyword {


  val keyw = {
    get[String]("keyword.blog")~
    get[String]("keyword.cat")~
    get[String]("keyword.word")~
  get[Long]("keyword.count") ~ 
  get[String]("keyword.summaryId") map {
    case blog~cat~word~count~summaryId => Keyword(blog,cat,word,count, summaryId)
  }
}

  def all(): List[Keyword] = DB.withConnection { implicit c =>
  SQL("select * from keyword").as(Keyword.keyw *)
}


def create(key: Keyword){DB.withConnection{implicit c=> 
  SQL("insert into keyword values({blog}, {cat}, {word},{count},{summaryId})").on('blog->key.blog,
      'cat -> key.cat,
      'word-> key.word,
      'count-> key.count,
      'summaryId -> key.summaryId).executeUpdate()
}
}

controllers/Application.scala

object Application extends Controller {

  val ta:Form[Keyword] = Form(
          mapping(
    "blog" -> nonEmptyText,
    "cat" -> nonEmptyText,
    "word" -> nonEmptyText,
    "count"-> of[Long],
    "summaryId"-> nonEmptyText
  )(Keyword.apply)(Keyword.unapply)
  )

  def index = Action {
    Ok(html.index(ta));
  }
  def newTask=  Action { implicit request =>
  ta.bindFromRequest.fold(
    errors => BadRequest(html.index(errors)),
    keywo => {

      Keyword.create(keywo)
      Ok(views.html.data(Keyword.all()))
    }
  )
}

- 当我正在使用h2-database时,它正在运行

- 当我使用MySQL时,它正在提供异常

给我一​​些解决这个问题的想法!

2 个答案:

答案 0 :(得分:1)

在app / helpers文件夹中创建AnormExtension助手。称之为AnormExtension.scala。代码如下:

object AnormExtension {

implicit def rowJavaLongToLong: Column[Long] = Column.nonNull { (value, meta) =>
  val MetaDataItem(qualified, nullable, clazz) = meta
    value match {
       case d: java.lang.Long => Right(d.longValue())
       case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass + " to Long for column " + qualified))
    }
  }
}

答案 1 :(得分:0)

尝试使用pgsql和anorm进行INSERT时,我经常会遇到此错误。我通过使用Sql String解析器来解决它。这可能对你有用......但不是100%肯定:

 def all(): List[Keyword] = DB.withConnection { implicit c =>
  SQL("select * from keyword").as(Keyword.keyw *).execute(SqlParser.scalar[String].singleOpt)
}