如何使用Criteria Builder实现Postgres TIMESTAMP与Unix时间的查询转换
解决方案
要解决Unix时间戳(Int类型)与Postgres TIMESTAMP字段的比较问题,核心是把数值型时间戳转换成数据库能识别的日期对象,再通过Criteria Builder构建查询条件,具体修改如下:
代码修正
假设你的Unix时间戳是秒级(Int类型通常存秒级,毫秒级会超出Int取值范围):
if (cmd.firstDate != null) { // 将Int秒级时间戳转为Instant对象 val startTime = Instant.ofEpochSecond(cmd.firstDate.toLong()) // 构建日期大于等于的查询条件 criteria.and(Criteria.where("myDate").greaterThanOrEquals(startTime)) }
如果数据库中的myDate是TIMESTAMP WITHOUT TIME ZONE类型,需要转为对应时区的LocalDateTime再比较:
if (cmd.firstDate != null) { val startTime = Instant.ofEpochSecond(cmd.firstDate.toLong()) // 根据数据库时区转换为LocalDateTime,这里用系统默认时区,可根据实际场景调整 val startLocalTime = LocalDateTime.ofInstant(startTime, ZoneId.systemDefault()) criteria.and(Criteria.where("myDate").greaterThanOrEquals(startLocalTime)) }
原代码问题说明
原代码直接用Int类型的时间戳和TIMESTAMP字段比较,属于类型不匹配——数据库会把数值当成普通数字而非时间,导致查询逻辑错误或抛出类型转换异常。必须先把时间戳转为Java的日期/时间对象(如Instant、LocalDateTime),Criteria Builder才能自动映射到Postgres的TIMESTAMP类型完成正确比较。
内容的提问来源于stack exchange,提问作者agingcabbage32
相关产品推荐
相关产品推荐

