映射列类型Slick 3.1.1

sja*_*der 2 scala slick

我是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)
  )

}
Run Code Online (Sandbox Code Playgroud)

在自动生成的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
}
Run Code Online (Sandbox Code Playgroud)

为了把它全部包起来,我使用这样:

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)
Run Code Online (Sandbox Code Playgroud)

我得到一个NullPointerException:隐式val myDateColumnType ....运行时.我已经验证了如果删除映射,最后一段代码就可以工作了.

Sun*_*dhu 5

尝试更改implicit valimplicit def您的定义MappedColumnTypes.之所以与Maksym Chernenko对这个问题给出的答案有关.通常,JdbcProfile驱动程序(定义api.MappedColumnType)尚未注入,并且:

导致NPE.您可以制作"mapper" val lazy,也可以将其更改valdef(如下所示)

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)
)
Run Code Online (Sandbox Code Playgroud)