gpt4 book ai didi

scala - 映射列类型 Slick 3.1.1

转载 作者:行者123 更新时间:2023-12-02 09:28:39 25 4
gpt4 key购买 nike

我是 Slick 的新手,很难将 java.sql.date/time/timestamp 的映射映射到 jodatime。

trait ColumnTypeMappings {

val profile: JdbcProfile
import profile.api._

val localTimeFormatter = DateTimeFormat.forPattern("HH:mm:ss")
val javaTimeFormatter = new SimpleDateFormat("HH:mm:ss")

implicit val myDateColumnType = MappedColumnType.base[LocalDate, Date](
ld => new java.sql.Date(ld.toDateTimeAtStartOfDay(DateTimeZone.UTC).getMillis),
d => new LocalDateTime(d.getTime).toLocalDate
)

implicit val myTimeColumnType = MappedColumnType.base[LocalTime, Time](
lt => new java.sql.Time(javaTimeFormatter.parse(lt.toString(localTimeFormatter)).getTime),
t => new LocalTime(t.getTime)
)

implicit val myTimestampColumnType = MappedColumnType.base[DateTime, Timestamp](
dt => new java.sql.Timestamp(dt.getMillis),
ts => new DateTime(ts.getTime, DateTimeZone.UTC)
)

}

在自动生成的 Tables.scala 中,我包含了这样的映射:

trait Tables extends ColumnTypeMappings {
val profile: slick.driver.JdbcDriver
import profile.api._
import scala.language.implicitConversions
// + rest of the auto generated code by slick codegen
}

总结一下,我是这样使用的:

object TestTables extends Tables {
val profile = slick.driver.MySQLDriver
}

import Tables._
import profile.api._

val db = Database.forURL("url", "user", "password", driver = "com.mysql.jdbc.Driver")
val q = Company.filter(_.companyid === 1).map(._name)
val action = q.result
val future = db.run(action)
val result = Await.result(future, Duration.Inf)

我得到一个 NullPointerException on: implicit val myDateColumnType.... 运行它时。如果删除映射,我已经验证了最后一段代码是否有效。

最佳答案

尝试在 MappedColumnTypes 的定义中将 implicit val 更改为 implicit def。之所以与Maksym Chernenko给出的答案有关对此question .通常,尚未注入(inject) JdbcProfile 驱动程序(定义 api.MappedColumnType),并且:

that causes NPE. You can either make your "mapper" val lazy, or change it from val to def (as shown below)

implicit def myDateColumnType = MappedColumnType.base[LocalDate, Date](
ld => new java.sql.Date(ld.toDateTimeAtStartOfDay(DateTimeZone.UTC).getMillis),
d => new LocalDateTime(d.getTime).toLocalDate
)

implicit def myTimeColumnType = MappedColumnType.base[LocalTime, Time](
lt => new java.sql.Time(javaTimeFormatter.parse(lt.toString(localTimeFormatter)).getTime),
t => new LocalTime(t.getTime)
)

implicit def myTimestampColumnType = MappedColumnType.base[DateTime, Timestamp](
dt => new java.sql.Timestamp(dt.getMillis),
ts => new DateTime(ts.getTime, DateTimeZone.UTC)
)

关于scala - 映射列类型 Slick 3.1.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35451513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com