我在Postgres 9.4中有一个表,其中包含电子邮件地址作为主键。使用Anorm,然后执行以下
DB.withConnection { implicit connection =>
SQL"insert into member_login_email(email, password) values ($email, $password)".executeInsert()
}
执行此操作时,会在表中输入正确的值,但会抛出TypeDoesNotMatch运行时异常:
at play.api.Application$class.handleError(Application.scala:296) ~[play_2.11-2.3.7.jar:2.3.7]
at play.api.DefaultApplication.handleError(Application.scala:402) [play_2.11-2.3.7.jar:2.3.7]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.11-2.3.7.jar:2.3.7]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.11-2.3.7.jar:2.3.7]
at scala.Option.map(Option.scala:145) [scala-library-2.11.1.jar:na]
Caused by: java.lang.RuntimeException: TypeDoesNotMatch(Cannot convert dsfsfadsf@ddd.com: class java.lang.String to Long for column ColumnName(member_login_email.email,Some(email)))
at scala.sys.package$.error(package.scala:27) ~[scala-library-2.11.1.jar:na]
at anorm.Sql$.anorm$Sql$$as(Anorm.scala:472) ~[anorm_2.11-2.3.7.jar:2.3.7]
at anorm.Sql$class.executeInsert(Anorm.scala:350) ~[anorm_2.11-2.3.7.jar:2.3.7]
at anorm.SimpleSql.executeInsert(Anorm.scala:190) ~[anorm_2.11-2.3.7.jar:2.3.7]
at repository.MemberLoginEmailRepository$$anonfun$create$1.apply(MemberLoginEmailRepository.scala:17) ~[classes/:na]
似乎Anorm期望主键为Long类型。有没有让Anorm接受Text类型的主键而不抛出异常?
我看过source code for Anorm,但一直在努力查看实际发生的情况。
答案 0 :(得分:8)
默认情况下,executeInsert()
使用ResultSetParser[Option[Long]]
来解析从数据库返回的主键。从scaladocs:
def executeInsert[A](generatedKeysParser: ResultSetParser[A] = SqlParser.scalar[Long].singleOpt)
要使用String
主键进行此操作,您可以使用此代码:
executeInsert(SqlParser.scalar[String].singleOpt)
这将返回Option[String]
。