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

Spring Boot 3.2迁移后H2原生查询无法正确处理LocalDateTime参数

Spring Boot 3.2迁移后H2原生SQL查询LocalDateTime参数无结果问题

场景概述

将应用从Spring Boot 2.3迁移至3.2版本,同时把H2数据库从1.4.200升级到2.2.224后,某原生SQL查询方法在测试环境返回空列表,相关现象如下:

  • 测试数据已通过@Sql注解预先填充,调用myEntityRepository.findAll()可看到所有记录且日期字段值正确
  • 移除原生SQL中的WHERE子句后,查询能返回全部数据;即使扩大时间范围至前后一年,带时间条件的原生查询仍无结果
  • 新增的派生查询方法findAllByCreatedBetween传入相同时间参数,可正常返回正确记录
  • 该逻辑在PostgreSQL生产环境运行正常,仅H2测试环境失效

相关代码片段

实体类

@Entity
public class MyEntity {
   // .... 其他属性
   private LocalDateTime created;
}

Repository原生查询方法

public interface MyEntityRepository extends JpaRepository<MissiveEntity, Long> {

   @Query(
      value = """
       with entities as (
       select * 
       from my_entity 
       where created >= :startTime
       )
       ....
      """,
      native = true
   )
   List<MyEntity> fetchAllWithoutAcknowledgement(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
}

Repository派生查询方法

List<MissiveEntity> findAllByCreatedBetween(LocalDateTime start, LocalDateTime end);

调试日志信息

  • Hibernate创建表语句:
Hibernate: 
    create table my_entity (
        created timestamp(6),
        id bigint not null,
        ...
        primary key (id),
    )
  • H2执行的SQL语句日志:
2024-05-24T18:31:57.130+03:00  INFO 1468150 --- [           main] h2database                               : jdbc[13] 
/*SQL l:1081 t:3*/with entities as (\n    SELECT *\n    FROM my_entity\n    WHERE created >= ?\n)... {1: TIMESTAMP '2024-04-17 07:59:00', 2: TIMESTAMP '2024-04-17 07:59:50'};

可见H2中created字段为timestamp(6)类型,Hibernate已将参数格式化为TIMESTAMP '2024-04-17 07:59:00',但条件匹配仍失效。

内容的提问来源于stack exchange,提问作者cooperok

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:05:01