You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Doobie无法构造含java.sql.Timestamp的case class的Read实例怎么办?

解决Doobie查询包含java.sql.Timestamp的Case Class问题

方法1:补充导入java.sql类型映射

Doobie对java.sql.Timestamp的支持需要额外导入对应类型的实例,在现有导入基础上添加javasql相关的implicits即可:

import doobie._
import doobie.implicits._
import doobie.postgres.implicits._
// 新增该行,引入java.sql系列类型的Read/Write实例
import doobie.implicits.javasql._

case class ExampleRow(id: String, ts: Timestamp)

val queryExampleRows = 
  sql"select * from example".query[ExampleRow].to[List]

导入后Doobie就能自动为ExampleRow生成Read实例,完成字段映射。

方法2:手动定义Read实例(兜底方案)

如果导入仍无效,可以手动为ExampleRow或Timestamp定义Read实例:

import java.sql.Timestamp
import doobie._
import doobie.implicits._
import doobie.postgres.implicits._

case class ExampleRow(id: String, ts: Timestamp)

// 直接为ExampleRow定义Read实例
implicit val exampleRowRead: Read[ExampleRow] = 
  Read[(String, Timestamp)].map { case (id, ts) => ExampleRow(id, ts) }

val queryExampleRows = 
  sql"select * from example".query[ExampleRow].to[List]

方法3:确保字段匹配

检查数据库表example的字段顺序、类型与ExampleRow完全对应:

  • 第一个字段需为字符串类型(如TEXT/VARCHAR)对应id: String
  • 第二个字段需为时间戳类型(如TIMESTAMP)对应ts: Timestamp
    若字段顺序不匹配,建议避免用select *,改为指定字段查询:
val queryExampleRows = 
  sql"select id, ts from example".query[ExampleRow].to[List]

内容的提问来源于stack exchange,提问作者Ramón J Romero y Vigil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 20:02:06