我想检索类型为DateTime的列的数据,我正在使用jodatime。即使我有自定义的TypeMapper,我也会遇到类型不匹配错误。
[error] C:\sample\modules\test\com\samp\user.scala:55: type mismatch;
[error] found : java.sql.Timestamp
[error] required: org.joda.time.DateTime
[error] result.nextTimestamp,
[error] ^
[error] one error found
这是代码
import org.specs2.mutable.Specification
import scala.slick.session.Database
import Database.threadLocalSession
import scala.slick.jdbc.{GetResult, StaticQuery => Q}
import Q.interpolation
import org.joda.time.DateTime
import scala.slick.lifted.{MappedTypeMapper,TypeMapper}
import java.sql.Timestamp
class UserSpec
extends Specification {
"User tests " should {
"get all the user data in db" in
new WithServer() {
val db = Database.forURL(url = "jdbc:h2:/path/to/db-file", driver = "com.mysql.jdbc.Driver")
implicit def dateTimeTypeMapper = MappedTypeMapper.base[DateTime, Timestamp] (
dateTime => new Timestamp(dateTime.getMillis()),
timeStamp => new DateTime(timeStamp)
)
case class user(
id: String,
name: String,
joinedAt: DateTime,
description: Option[String]
)
implicit val getUserResult: GetResult[user] =
GetResult( result =>
user(
result.nextString,
result.nextString,
result.nextTimestamp,
result.nextStringOption)
)
db withSession {
val usr = Q.queryNA[user]("SELECT * FROM user").list()
usr foreach println
}
}
}
}
我不确定为什么这不起作用。非常感谢任何帮助或指示。
答案 0 :(得分:1)
这里的问题是result.nextTimestamp
返回java.sql.Timestamp
(result
是JDBC ResultSet
)。如果你想把它变成DateTime
,我认为它有一个构造函数。所以你要写:
implicit val getUserResult: GetResult[user] =
GetResult( result =>
user(
result.nextString,
result.nextString,
new DateTime(result.nextTimestamp),
result.nextStringOption)
)