Slick - 将Long隐式转换为java.sql.Timestamp

时间:2015-11-12 21:20:09

标签: postgresql scala slick

Slick 2.1 Scala 2.11.7

无法获得Long< - >的隐式转换java.sql.Timestamp或java.sql.Date工作。我让他们为其他转换工作,例如JodaTime.DateTime< - >的java.sql.Timestamp ...

例如,在查询时返回错误:

org.postgresql.util.PSQLException: ERROR: operator does not exist: 
timestamp with time zone >= bigint Hint: No operator matches 
the given name and argument type(s). You might need to add explicit type casts. 
Position: 325

这些是暗示,它们肯定是在范围内正确导入的:

implicit val LongToTimestamp = MappedColumnType.base[Long, Timestamp](
longTS => new Timestamp(longTS),
sqlTS => sqlTS.getTime
)

implicit val LongToDate = MappedColumnType.base[Long, java.sql.Date](
longTS => new java.sql.Date(longTS),
sqlDate => sqlDate.getTime
)

我也尝试过使用java.lang.Long:

implicit val LongToTimestamp = MappedColumnType.base[java.lang.Long, Timestamp](
longTS => new Timestamp(longTS),
sqlTS => sqlTS.getTime
)

implicit val LongToDate = MappedColumnType.base[java.lang.Long, java.sql.Date](
longTS => new java.sql.Date(longTS),
sqlDate => sqlDate.getTime
)

我在这里缺少什么?谢谢!

-

其他信息:

查询方法定义为(排队是java.sql.Timestamp):

def getJobs(jobTypeId: Short, onOrAfter: DateTime): Seq[JobRow] = {
 val q1 = for{j <- Jobs if j.jobTypeId === jobTypeId && j.queued >= onOrAfter.getMillis} yield j
 db.withSession{ implicit s =>
   q1.buildColl[Seq]
 }
}

表格定义:

class Jobs(tag: Tag) extends Table[JobRow](tag, "job") {

def jobId = column[Long]("job_id", O.PrimaryKey, O.NotNull)

def jobTypeId = column[Short]("job_type_id", O.NotNull)

def queued = column[Long]("queued", O.NotNull)

def * = (jobId, jobTypeId, queued) <>((JobRow.apply _).tupled, JobRow.unapply_ )

def pk = primaryKey("job_pk", jobId)
}

1 个答案:

答案 0 :(得分:0)

您的问题是,Postgres中的基础queued列不是bigint而是timestamp with time zone。但是,在Slick的Jobs表定义中,您说该列是Long。 Slick已经知道如何将Long绑定到查询,因此它永远不会尝试使用您的隐式将Long转换为它知道如何绑定的另一种类型。

理想情况下,您只需使用sql.Timestamp作为Jobs.queued列类型(您对查询代码段的评论似乎表明您认为):< / p>

def queued = column[Timestamp]("queued", O.NotNull)
// As opposed to your example where this is
// def queued = column[Long]("queued", O.NotNull)

或者,您可以为to_timestamp(double)

创建一个Slick包装器
val toTimestamp = SimpleFunction.unary[Double, Timestamp]("to_timestamp")
val q1 = for {
  j <- Jobs
  if j.jobTypeId === jobTypeId && j.queued >= toTimestamp(onOrAfter.getMillis)
} yield j

最后,您可以向Postgres DB添加自动转换以进行转换。